Search code examples
androidandroid-permissionsandroid-10.0

permissions not working for android 10 in android studio


Currently, I was trying to build an app that requires 3 permissions: Reading, writing, and camera. I am using the following code for that.

in Main Activity:

String[] permissions = new String[]{
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
};
private int PERMISSION_REQUEST_CODE = 10

public boolean hasPermissions(Context context, String[] permissions) {
    if (context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}

and in onCreate() method, I am using the following:

    if (!hasPermissions(this, permissions)) {
        ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
    }

below is the code for onRequestPermissionResult() method:

@SuppressLint("MissingPermission")
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == PERMISSION_REQUEST_CODE) {
        if (!hasPermissions(this, permissions)) {
            finish();
        } else {
            view_camera.bindToLifecycle(lifecycleOwner);
            view_camera.setPinchToZoomEnabled(true);
            view_camera.setFocusable(true);
        }
    }
}

Everything working fine till android 9, but in android 10, it is not able to read data from storage, and also not able to store it.

Does anyone know the reason behind this?

I have added the permissions to the Manifest file as well.


Solution

  • Add android:requestLegacyExternalStorage="true" in manifest under <application like

    <application
        android:requestLegacyExternalStorage="true"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">