定位android O(26) 8.0 后如何读取+写入外部存储

How to have Read + Write external storage after targeting android O (26) 8.0

在瞄准 android 之前,下面的 O 代码运行良好。设置 targetApi=27 (8.1) 后停止工作。

context.requestPermissions(new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        requestCode);

我看到一个众所周知的权限对话框,我很乐意允许 App 访问设备上的照片媒体和文件。

并且在 onRequestPermissionResult() 它 returns

android.permission.READ_EXTERNAL_STORAGE == 0, 
android.permission.WRITE_EXTERNAL_STORAGE == -1

我按照这个答案 没有用。

当我在寻找解决方案时,发现了这个 https://developer.android.com/about/versions/oreo/android-8.0-changes.html#rmp 阅读后我并不聪明,但我 100% 确定这是导致它的原因。

If the app targets Android 8.0 (API level 26), the system grants only READ_EXTERNAL_STORAGE at that time; however, if the app later requests WRITE_EXTERNAL_STORAGE, the system immediately grants that privilege without prompting the user.

我试过只请求读取权限(dialog-> allow) 后来我请求写入权限(no dialog -> still not granted) 它没有用。

清单:

<!-- Internet Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<!-- I added now, -->
<uses-permission android:name="android.permission.CAMERA"/>

<!-- Storage Permissions -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<!-- Account Access Permission -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />

<!-- Vibrate used for notification updates -->
<uses-permission android:name="android.permission.VIBRATE" />

我需要获得许可

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra("output", outputDestination);

好吧,我终于知道发生了什么了,看完之后我终于可以继续了。

问题是 HockeyApp 在清单中有:

<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    android:maxSdkVersion="18" />

合并清单后,应用中没有 WRITE_EXTERNAL_STORAGE 权限。由于 android 系统

中的错误,该应用程序之前可以正常工作

Prior to Android 8.0 (API level 26), if an app requested a permission at runtime and the permission was granted, the system also incorrectly granted the app the rest of the permissions that belonged to the same permission group, and that were registered in the manifest.

由于 Android 系统中的错误,它之前工作正常,因为我们请求读取权限

我所做的只是在我的主应用程序清单中进行了更改

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    tools:remove="android:maxSdkVersion" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:remove="android:maxSdkVersion"/>

并添加

android:requestLegacyExternalStorage="true" 

申请