-2

I have a file at /sdcard/myfolder/filename.txt

I access this file in my source code as follows:

File fileMyTextFile = new File("/sdcard/myfolder/file.txt");  

At one point I check to see if the file exists before opening it to read it's data:

        try {
            if (fileMyTextFile.exists()) {
              ...
            }
        } catch (FileNotFoundException e) {
            Log.d("MyApp", "file not found");
            e.printStackTrace();
        }

I keep getting the FileNotFoundException when my code reaches this point. This same code works without any changes in my other phones which have a lower version of android so I think this has to be something to do with app permissions.

I have declared these in AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  

I also have

<application
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    android:requestLegacyExternalStorage="true"
    tools:ignore="AllowBackup,GoogleAppIndexingWarning">
    ....

In MainActivity.java I have also done this:

    ActivityCompat.requestPermissions(this,
            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }, MY_PERMISSIONS_REQUEST );

How do I access my custom files in android 13?

user13267
  • 6,871
  • 28
  • 80
  • 138
  • Use not only File.exists() but also File.canRead() before trying to read the file. – blackapps Feb 15 '23 at 10:06
  • And tell us who and how your custom file was put there. Your code will fail on all Android 11+ devices. – blackapps Feb 15 '23 at 10:07
  • `I have a file at /sdcard/myfolder/filename.txt` Who gave you that path? If you try to get that path programmatically it would have been `/storage/emulated/0/myfolder/...` – blackapps Feb 15 '23 at 10:09
  • `In MainActivity.java I have also done this:` Well you should not ask READ and WRITE access if your app runs on an Android 13+ device. – blackapps Feb 15 '23 at 10:11
  • I had similar issue and fixed it; check my post https://stackoverflow.com/questions/75080617/api-33-android-13-non-media-files-not-found – MOTIVECODEX Feb 15 '23 at 10:14

1 Answers1

0

For Android 13 the request all files permissions has to be shown at runtime. The following code is of course not the full thing, but the main thing needed is to request the request all files permission in the onCreate

In MainActivity:

public static final int STORAGE_PERMISSION = 0,
            ALL_FILES_PERMISSION = 2;

private void checkForExternalPermission() {
  if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
    requestAllFilesAccess(this);
  }
}

public void requestAllFilesAccess(@NonNull final OnPermissionGranted onPermissionGranted) {
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setTitle("Grant all files permissions!");
    alertDialogBuilder.setMessage("You need to grant all files permission");
    alertDialogBuilder.setCancelable(false);

    alertDialogBuilder.setPositiveButton("Grant", (dialog, id) -> {

        permissionCallbacks[ALL_FILES_PERMISSION] = onPermissionGranted;
        try {
          Intent intent =
            new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
            .setData(Uri.parse("package:" + getPackageName()));
          startActivity(intent);
        } catch (Exception e) {
          Log.e("MainActivity", "Failed to initial activity to grant all files access", e);
          Toast.makeText(this, "Failed to grant permissions", Toast.LENGTH_SHORT).show();
        }

        this.finish();
      })

      .setNegativeButton("Cancel", (dialog, id) -> dialog.cancel());

    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
  }
}
MOTIVECODEX
  • 2,624
  • 14
  • 43
  • 78
  • Does this go in MainActivity.java? When is checkForExternalPermission() called? – user13267 Feb 15 '23 at 10:18
  • I had the first method of the example in MainActivity and the second in PermissionActivity, but you can also add both in MainActivity to make it easier. The class also has to implement `implements ActivityCompat.OnRequestPermissionsResultCallback` and you have to import the needed classes etc. – MOTIVECODEX Feb 15 '23 at 10:23
  • I need to make a separate PermissionActivity.java file? – user13267 Feb 15 '23 at 10:24
  • That's not required, but that way I keep my MainActivity cleaner. It's basically more like a PermissionUtil.java, I named it PermissionActivity – MOTIVECODEX Feb 15 '23 at 10:25
  • For now it seems to do what I want if I just downgrade targetSdkVersion to 29 in app build.gradle, but I'll check this code out as well – user13267 Feb 15 '23 at 10:27
  • Is checkForExternalPermission() supposed to be called in onCreate()? – user13267 Feb 15 '23 at 10:28
  • Yes, checkForExteralPermission is called in onCreate – MOTIVECODEX Feb 15 '23 at 10:35