The application cannot write to external memory on Android 6.0 (I am testing an emulator), even after WRITE_EXTERNAL_STORAGE was provided at runtime; if the application will not be killed and restarted.
Snippet from 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 }
Whenever I need to write to external storage (for backup), I check if I have permission.
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()); }
I also have
@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(); } } }
When permission is granted by the user, the following code
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());
produces
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)
If, after obtaining permission, the application is killed and restarted, everything will be perfect, and the backup file will be created in external storage.
Please suggest what I am doing wrong.