SemyColon.Me
SemyColon.Me

Reputation: 378

How to open a file in another app in API 24 and above - andorid

i have a file's path and i want the device to open the file with another app

 public static void openUrl(Context context, String path) {
    Uri uriForFile;
    if  (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
        uriForFile = GenericFileProvider.getUriForFile(context,"xyz.provider",new File(path));
    }else{
        uriForFile = Uri.fromFile(new File(path));
    }
    MimeTypeMap myMime = MimeTypeMap.getSingleton();
    Intent newIntent = new Intent(Intent.ACTION_VIEW);
    String mimeType = myMime.getMimeTypeFromExtension(fileExt(path).substring(1));
    newIntent.setDataAndType(uriForFile, mimeType);
    newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    try {
        context.startActivity(newIntent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(context, R.string.msg_noHandlerForThisTypeOfFile, Toast.LENGTH_LONG).show();
    }
}

the above code works well on api 23 and lower

but in android 7 when i want to open a mp3 file for example it Toast "the player doesn't support this type of audio file"

or when i open a image it open a blank page with gallery app.

Upvotes: 1

Views: 527

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006674

Replace:

newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

with:

newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_GRANT_READ_URI_PERMISSION);

Right now, the third-party app has no rights to your GenericFileProvider content.

Upvotes: 2

Related Questions