Android 无法从Oreo中的SD卡拾取文件

Android 无法从Oreo中的SD卡拾取文件,android,Android,我是Android新手,正在开发一项功能,其中我必须从内部存储和SD卡中提取文件。我已经实现了一些代码。在下面代码的帮助下,我能够从Android pie版本9 API level 28和Android Nougat版本7的SD卡和内部存储中提取或选择文件,但我无法从Android Oreo8 API level 26版本的SD卡中获取pdf文件,对于棉花糖,它无法从内部和SD卡中选择文件。我想不出是什么问题。同一代码对一个代码有效,而对另一个代码无效。有任何通用的方式访问文件PDF和图像。提前

我是Android新手,正在开发一项功能,其中我必须从内部存储和SD卡中提取文件。我已经实现了一些代码。在下面代码的帮助下,我能够从Android pie版本9 API level 28和Android Nougat版本7的SD卡和内部存储中提取或选择文件,但我无法从Android Oreo8 API level 26版本的SD卡中获取pdf文件,对于棉花糖,它无法从内部和SD卡中选择文件。我想不出是什么问题。同一代码对一个代码有效,而对另一个代码无效。有任何通用的方式访问文件PDF和图像。提前感谢

下面是实现的代码

    private void SelectFileFromGallery(){
              Intent intent = new Intent();
                        String[] mimeTypes = {"image/*", "application/pdf"};
                        intent.setType("*/*");
                        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
                        intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                        intent.addCategory(Intent.CATEGORY_OPENABLE);
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        startActivityForResult(Intent.createChooser(intent, getString(R.string.select_file)), SELECT_FILE);
            }

            public void onActivityResult(int requestCode, int resultCode, Intent data) {
                    super.onActivityResult(requestCode, resultCode, data);

                    if (resultCode == Activity.RESULT_OK) {
                         if (requestCode == SELECT_FILE) {
                            onSelectFileFromGalleryResult(data);
                            isUpdated = true;

                    } else if (requestCode == 11) {
                        onBackPressed();
                    }
                }

        private void onSelectFileFromGalleryResult(Intent data) {
                try {
                    InputStream is;

                    Uri selectedImageUri = data.getData();

                    String file= AndroidUtilities.getFilePath(selectedImageUri);
                    File imageFile = new File(file);
                    Log.d("File Path",imageFile.getAbsolutePath());
                    if (imageFile.exists()) {
        // Here I am Compressing the file to store
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
    public static String getFilePath(final Uri uri) {

            String filePath="";
            try {
               final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
                if (isKitKat && DocumentsContract.isDocumentUri(MyApp.applicationContext, uri)) {
                    if (isExternalStorageDocument(uri)) {
                        final String docId = DocumentsContract.getDocumentId(uri);
                        final String[] split = docId.split(":");
                        final  String type=split[0];
                         String storageDefinition;


    //                    if ("primary".equalsIgnoreCase(type)) {
    //                        return Environment.getExternalStorageDirectory() + "/" + split[1];
    //                    } else {
    //
    //                        if(Environment.isExternalStorageRemovable()){
    //                            storageDefinition = "EXTERNAL_STORAGE";
    //
    //                        } else{
    //                            storageDefinition = "SECONDARY_STORAGE";
    //                        }
    //
    //                        return System.getenv(storageDefinition) + "/" + split[1];
    //                    }

                        if("primary".equalsIgnoreCase(type)){
                        if (split.length > 1) {
                            return Environment.getExternalStorageDirectory() + "/" + split[1];
                        } else {
                            return Environment.getExternalStorageDirectory() + "/";
                        }
                        // This is for checking SD Card
                    }
                        else if ("home".equalsIgnoreCase(type)) {
                            return Environment.getExternalStorageDirectory() + "/documents/" + split[1];
                        }
                        else {

                            return "storage" + "/" + docId.replace(":", "/");

                    }

                    } else if (isDownloadsDocument(uri)) {
                        String fileName = getFileName(MyApp.applicationContext, uri);
                        final String id = DocumentsContract.getDocumentId(uri);

                        if(fileName!=null){
                            return Environment.getExternalStorageDirectory().toString()+"/Download/"+fileName;
                        }

                        if (id != null && id.startsWith("raw:")) {
                            return id.substring(4);
                        }

                        String[] contentUriPrefixesToTry = new String[]{
                                "content://downloads/public_downloads",
                                "content://downloads/my_downloads",
                                "content://downloads/all_downloads",

                        };

    //                    final Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefixesToTry), Long.valueOf(id));
    //                    return getDataColumn(MyApp.applicationContext, contentUri, null, null);
                        for (String contentUriPrefix : contentUriPrefixesToTry) {
                            Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
                            try {
                                String path = getDataColumn(MyApp.applicationContext, contentUri, null, null);
                                if (path != null) {
                                    return path;
                                }
                            } catch (Exception e) {}
                        }

    //                    File cacheDir = getDocumentCacheDir(MyApp.applicationContext);
    //                    File file = generateFileName(fileName, cacheDir);
    //                    String destinationPath = null;
    //                    if (file != null) {
    //                        destinationPath = file.getAbsolutePath();
    //                        saveFileFromUri(MyApp.applicationContext, uri, destinationPath);
    //                    }

    //                    return destinationPath;

                    } else if (isMediaDocument(uri)||isMediaStorage(uri)) {
                        final String docId = DocumentsContract.getDocumentId(uri);
                        final String[] split = docId.split(":");
                        final String type = split[0];

                        Uri contentUri = null;
                        switch (type) {
                            case "image":
                                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                                break;
                            case "video":
                                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                                break;
                            case "audio":
                                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                                break;
                        }

                        final String selection = "_id=?";
                        final String[] selectionArgs = new String[]{
                                split[1]
                        };

                        return getDataColumn(MyApp.applicationContext, contentUri, selection, selectionArgs);
                    }
                } else if ("content".equalsIgnoreCase(uri.getScheme())) {
                    return getDataColumn(MyApp.applicationContext, uri, null, null);
                } else if ("file".equalsIgnoreCase(uri.getScheme())) {
                    return uri.getPath();
                }
            } catch (Exception e) {
                Log.e("Exception", e.toString());
            }
            return null;

        }

 private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {MediaStore.Images.Media.DATA};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                String value = cursor.getString(column_index);
                if (value.startsWith("content://") || !value.startsWith("/") && !value.startsWith("file://")) {
                    return null;
                }
                return value;
            }
        } catch (Exception e) {
            Log.e("Exception", e.toString());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    private static boolean isMediaStorage(Uri uri) {
        return "com.google.android.apps.docs.storage".equals(uri.getAuthority());
    }

intent.addFlagsInt.FLAG\授予\读取\ URI\权限。拆下那条线。这毫无意义。你不能授予任何东西,因为你不是老板。因此用户可以选择一个文件,并且不会触发onActivityResult。你是这么说的吗?intent.putExtraIntent.EXTRA_MIME_类型你仍然拥有它,同时你也把MIME类型*/*。这没有道理,你以前都问过这个问题。但是当你第一次抱怨你不能选择pdf文件时。现在你抱怨你不能从sd卡中选择,但仍然提到pdf。现在还不清楚您真正的问题是什么。@Oreo中的blackapps每当我尝试从SDCARD中选择文件时,getFilePath方法返回一些路径,在Oreo android版本中,path无法找到该文件,但在Nougat和pie中它可以找到。