Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 733
YogeshM Avatar asked Oct 11 '15 05:10

YogeshM


People also ask

How do I grant permission to write external storage?

To read and write data to external storage, the app required WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE system permission. These permissions are added to the AndroidManifest. xml file. Add these permissions just after the package name.

What is external storage permission?

When an app is granted storage permission, it can access the device storage at any time. This means it can upload personal files or even delete sensitive information from the device, so it's better to think twice before giving storage permission to untrusted apps, as it can be harmful.

What is storage permission not granted?

If permission isn't granted, no files stored locally on the device can be indexed and added to the library database. You can verify that the storage permission has been denied in the app details page in Android Settings as "No permissions granted" will appear in the Permissions section.

What is app storage permission?

As the name suggests, permissions govern what an app is allowed to do and access. This ranges from reading the data stored on your phone, such as contacts and media files, through to using hardware including your handset's camera or microphone. Granting permission allows the app to use the feature.


1 Answers

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).

like image 180
Harish Sharma Avatar answered Nov 09 '22 13:11

Harish Sharma