YogeshM
YogeshM

Reputation: 147

Can't write to external storage unless app is restarted after granting permission

App unable to write to external storage on Android 6.0 (I'm testing on emulator), even after WRITE_EXTERNAL_STORAGE has been granted at runtime; unless the app is 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 whether or not 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 the following

    @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 the permission is granted by 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 the permission is granted, the app is killed and restarted, everything goes perfect and backup file is created in external storage.

Please suggest what I am doing wrong.

Upvotes: 10

Views: 3583

Answers (2)

Cosmin Badulescu
Cosmin Badulescu

Reputation: 235

Try to emulate a new device (for example a 6.0 x86_64 with Google api's). I had the exact same problem and i resolved it by running on a different emulator.

Upvotes: -1

Harish Sharma
Harish Sharma

Reputation: 370

Add the following line in onRequestPermissionsResult() method after checking permission grant successfully.

android.os.Process.killProcess(android.os.Process.myPid());

Edit: Check you have set the target sdk version to 23.if You already have done that and it is not working(or you don't want to set it to 23) than you may go with this solution(killing the app process).

Upvotes: 3

Related Questions