Android 从外部SD卡(USB OTG存储)拾取图像文件

Android 从外部SD卡(USB OTG存储)拾取图像文件,android,Android,我看到这个问题: 但它没有回答我的问题。我有一个外部SD卡,我想从我的应用程序访问它,并将图像从它复制到一个内部存储器。这可能吗? 我正在使用android nouget 这就是我到目前为止所做的 public static List<StorageInfo> getStorageList() { List<StorageInfo> list = new ArrayList<StorageInfo>(); String de

我看到这个问题:


但它没有回答我的问题。我有一个外部SD卡,我想从我的应用程序访问它,并将图像从它复制到一个内部存储器。这可能吗? 我正在使用android nouget

这就是我到目前为止所做的

public static List<StorageInfo> getStorageList() {

        List<StorageInfo> list = new ArrayList<StorageInfo>();
        String def_path = Environment.getExternalStorageDirectory().getPath();
        boolean def_path_removable = Environment.isExternalStorageRemovable();
        String def_path_state = Environment.getExternalStorageState();
        boolean def_path_available = def_path_state.equals(Environment.MEDIA_MOUNTED)
                || def_path_state.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
        boolean def_path_readonly = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY);

        HashSet<String> paths = new HashSet<String>();
        int cur_removable_number = 1;

        if (def_path_available) {
            paths.add(def_path);
            list.add(0, new StorageInfo(def_path, def_path_readonly, def_path_removable, def_path_removable ? cur_removable_number++ : -1));
        }

        BufferedReader buf_reader = null;
        try {
            buf_reader = new BufferedReader(new FileReader("/proc/mounts"));
            String line;
            Log.d(TAG, "/proc/mounts");
            while ((line = buf_reader.readLine()) != null) {
                Log.d(TAG, line);
                if (line.contains("vfat") || line.contains("/mnt")) {
                    StringTokenizer tokens = new StringTokenizer(line, " ");
                    String unused = tokens.nextToken(); //device
                    String mount_point = tokens.nextToken(); //mount point
                    if (paths.contains(mount_point)) {
                        continue;
                    }
                    unused = tokens.nextToken(); //file system
                    List<String> flags = Arrays.asList(tokens.nextToken().split(",")); //flags
                    boolean readonly = flags.contains("ro");

                    if (line.contains("/dev/block/vold")) {
                        if (!line.contains("/mnt/secure")
                                && !line.contains("/mnt/asec")
                                && !line.contains("/mnt/obb")
                                && !line.contains("/dev/mapper")
                                && !line.contains("tmpfs")) {
                            paths.add(mount_point);
                            list.add(new StorageInfo(mount_point, readonly, true, cur_removable_number++));
                        }
                    }
                }
            }

        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (buf_reader != null) {
                try {
                    buf_reader.close();
                } catch (IOException ex) {}
            }
        }
        return list;
    }





    void open()
    {

        String sdCardPath = getStorageList().get(1).path+"/DCIM/100_FLIR/"; //placed it statically for now...

        File imagesFolder = new File(Environment.getExternalStorageDirectory(), context.getString(R.string.FolderName));
        if (!imagesFolder.exists())
        {
            imagesFolder.mkdirs();
        }

        String timeStamp = new SimpleDateFormat("yyMMdd_HHmmss", Locale.ENGLISH).format(new Date());
        File image = new File(imagesFolder, "IM_" + timeStamp + ".jpeg");

        imagepath = image.getAbsolutePath();
        Uri uriImagePath = GlobalFunctions.getFileURI(context,image);


        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        Uri uri = Uri.parse(path);
        intent.setDataAndType(uri, "*/*");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,uriImagePath);
        intent.putExtra("return-data", true);
        startActivityForResult(intent,458);


    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 458 && resultCode == Activity.RESULT_OK)
        {
            File f = new File(imagepath);
            try {
                f.createNewFile();
                copyFile(new File(getRealPathFromURI_API19(this,data.getData())), f); //getRealPathFromURI_API19 is returning empty for files on sd card
            } catch (IOException e) {
                globalVariables.AppLogging(GlobalVariables.ERROR_GENERAL_MSG_LOG,e.toString(), LogFileName.ErrorLogFilename);
            }
        }

    public static String getRealPathFromURI_API19(Context context, Uri uri) {
        String filePath = "";

        // Image pick from recent
        String wholeID = DocumentsContract.getDocumentId(uri);

        // Split at colon, use second item in the array
        String id = wholeID.split(":")[1];

        String[] column = {MediaStore.Images.Media.DATA};

        // where id is equal to
        String sel = MediaStore.Images.Media._ID + "=?";

        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                column, sel, new String[]{id}, null);

        int columnIndex = cursor.getColumnIndex(column[0]);

        if (cursor.moveToFirst()) {
            filePath = cursor.getString(columnIndex);
        }
        cursor.close();
        return filePath;


    }
void copyFile(File sourceFile, File destFile) throws IOException {
        if (!sourceFile.exists()) {
            return;
        }
        FileChannel source = null;
        FileChannel destination = null;
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();
        if (destination != null && source != null) {
            destination.transferFrom(source, 0, source.size());
        }
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
公共静态列表getStorageList(){ 列表=新的ArrayList(); 字符串def_path=Environment.getExternalStorageDirectory().getPath(); 布尔def_path_removable=Environment.isExternalStorageRemovable(); 字符串def_path_state=Environment.getExternalStorageState(); 布尔def_path_available=def_path_state.equals(Environment.MEDIA_MOUNTED) ||def_path_state.equals(环境、媒体、挂载、只读); 布尔def_path_readonly=Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_readonly); HashSet路径=新的HashSet(); int cur\u可移动\u编号=1; 如果(定义路径可用){ 添加(定义路径); 列表.添加(0,新的存储信息(定义路径,定义路径只读,定义路径可移动,定义路径可移动?当前可移动编号++:-1)); } BufferedReader buf_reader=null; 试一试{ buf_reader=newbufferedreader(newfilereader(“/proc/mounts”); 弦线; Log.d(标记“/proc/mounts”); while((line=buf_reader.readLine())!=null){ Log.d(标签、行); if(line.contains(“vfat”)| | line.contains(“/mnt”)){ StringTokenizer令牌=新的StringTokenizer(行“”); String unused=tokens.nextToken();//设备 String mount_point=tokens.nextToken();//装入点 if(路径包含(装入点)){ 继续; } unused=tokens.nextToken();//文件系统 列表标志=Arrays.asList(tokens.nextToken().split(“,”);//标志 boolean readonly=flags.contains(“ro”); if(行包含(“/dev/block/vold”)){ 如果(!line.contains(“/mnt/secure”) &&!line.contains(“/mnt/asec”) &&!line.contains(“/mnt/obb”) &&!line.contains(“/dev/mapper”) &&!line.contains(“tmpfs”)){ 路径。添加(挂载点); 添加(新的存储信息(装入点、只读、真、当前可移动\u编号++); } } } } }捕获(FileNotFoundException ex){ 例如printStackTrace(); }捕获(IOEX异常){ 例如printStackTrace(); }最后{ if(buf_读取器!=null){ 试一试{ buf_reader.close(); }catch(IOException ex){} } } 退货清单; } 空开() { 字符串sdCardPath=getStorageList().get(1).path+“/DCIM/100_FLIR/”;//暂时静态放置它。。。 File imagesFolder=新文件(Environment.getExternalStorageDirectory(),context.getString(R.string.FolderName)); 如果(!imagesFolder.exists()) { imagesFolder.mkdirs(); } String timeStamp=new SimpleDateFormat(“yymdd_HHmmss”,Locale.ENGLISH).format(new Date()); 文件图像=新文件(imagesFolder,“IM_”+timeStamp+“.jpeg”); imagepath=image.getAbsolutePath(); Uri URIMAGEPATH=GlobalFunctions.getFileURI(上下文,图像); 意向意向=新意向(意向.行动\u获取\u内容); Uri=Uri.parse(路径); intent.setDataAndType(uri,“*/*”); intent.putExtra(MediaStore.EXTRA_输出,uriImagePath); intent.putExtra(“返回数据”,true); startActivityForResult(意向书,458); } 受保护的void onActivityResult(int请求代码、int结果代码、意图数据) { super.onActivityResult(请求代码、结果代码、数据); if(requestCode==458&&resultCode==Activity.RESULT\u确定) { 文件f=新文件(imagepath); 试一试{ f、 createNewFile(); copyFile(新文件(getRealPathFromURI_API19(this,data.getData())),f);//对于sd卡上的文件,getRealPathFromURI_API19返回空 }捕获(IOE异常){ globalVariables.apploging(globalVariables.ERROR\u GENERAL\u MSG\u LOG,例如toString(),LogFileName.ErrorLogFilename); } } 公共静态字符串getRealPathFromURI_API19(上下文,Uri){ 字符串filePath=“”; //从最近的图像中拾取图像 字符串wholeID=DocumentsContract.getDocumentId(uri); //在冒号处拆分,使用数组中的第二项 字符串id=wholeID.split(“:”[1]; String[]column={MediaStore.Images.Media.DATA}; //其中id等于 字符串sel=MediaStore.Images.Media._ID+“=?”; Cursor Cursor=context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL\u CONTENT\u URI, 列,sel,新字符串[]{id},null); int columnIndex=cursor.getColumnIndex(列[0]); if(cursor.moveToFirst()){ filePath=cursor.getString(columnIndex); } cursor.close(); 返回文件路径; } void copyFile(File sourceFile,File destFile)引发IOException{ 如果(!sourceFile.exists()){ 返回; } filechannelsource=null; filechanneldestination=null; source=新文件输入流(sourceFile).getChannel(); destination=新文件输出流(destFile).getChannel(); if(目标!=null&&source!=null){ destination.transferFrom(source,0,source.size()); }