【发布时间】:2016-01-08 19:17:18
【问题描述】:
即使在运行时授予 WRITE_EXTERNAL_STORAGE 之后,应用程序也无法写入 Android 6.0 上的外部存储(我正在模拟器上进行测试);除非应用程序被杀死并重新启动。
来自 AndroidManifest.xml 的片段
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
build.gradle
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
......
minSdkVersion 15
targetSdkVersion 23
}
每当我需要写入外部存储(用于备份)时,我都会检查我是否有权限。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
getActivity().getBaseContext().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_RW_EXTERNAL_STORAGE);
mPendingAction = PendingAction.Backup;
} else {
BackupRestoreService.startBackup(getActivity().getBaseContext());
}
我也有以下
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.d("SettingsActivity", "grantResultsLength: " + grantResults.length);
if (requestCode == PERMISSION_REQUEST_RW_EXTERNAL_STORAGE) {
Log.d("SettingsActivity", "grantResultsLength: " + grantResults.length);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
switch (mPendingAction) {
case Backup:
BackupRestoreService.startBackup(getActivity().getBaseContext());
mPendingAction = PendingAction.None;
break;
case Restore:
break;
default:
}
} else {
Toast.makeText(getActivity(),
"Permission denied",
Toast.LENGTH_SHORT).show();
}
}
}
当用户授予权限时,如下代码
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), DIR_MY_PORTFOLIO);
if (!file.mkdirs())
Log.d("Backup", "Unable to create directories");
final String outputFilename = new SimpleDateFormat("'Backup'-yyyyMMdd-hhmmss'.mpb'", Locale.US).format(new Date());
File outputFile = new File(getBackupStorageDir(), outputFilename);
Log.d("Backup", "Can write to file: " + outputFile.canWrite());
Log.d("Backup", "File exists: " + outputFile.exists());
生产
in.whoopee.myportfolio D/Backup: Unable to create directories
in.whoopee.myportfolio D/Backup: Can write to file: false
in.whoopee.myportfolio D/Backup: File exists: false
in.whoopee.myportfolio W/System.err: java.io.FileNotFoundException: /storage/09FD-2F0C/Download/My Portfolio/Backup-20151011-051318.mpb: open failed: EACCES (Permission denied)
如果在授予权限后,应用程序被杀死并重新启动,一切都会完美,并在外部存储中创建备份文件。
请指出我做错了什么。
【问题讨论】:
-
这是一个众所周知的错误。您可以在开发者预览问题跟踪器中查看问题。我们对此无能为力。
-
感谢指点
标签: android android-permissions android-6.0-marshmallow