TooManyEduardos TooManyEduardos - 3 months ago 20
Android Question

Intent.putExtra() prompts the wrong third party app

I'm migrating the code from

Intent.setDataAndType()
to
Intent.putExtra()
, but I can't get the same result.

I'm also handling the data differently for android N than for the rest of the OS levels.

Here's my code:

// coming to this method
final FileType fileType
final File file;

final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

intent.putExtra(Intent.EXTRA_INTENT, FileProvider.getUriForFile(MyApplication.getAppContext(), MyApplication.getAppContext().getApplicationContext().getPackageName() + ".provider", file));
//intent.setDataAndType(FileProvider.getUriForFile(MyApplication.getAppContext(), MyApplication.getAppContext().getApplicationContext().getPackageName() + ".provider", file), fileType.getMimeType());
} else {
intent.putExtra(Intent.EXTRA_INTENT, Uri.fromFile(file));
intent.putExtra(Intent.EXTRA_MIME_TYPES, fileType.getMimeType());
//intent.setDataAndType(Uri.fromFile(file), fileType.getMimeType());
}

startActivity(intent);


The problem is that this is trying to open the wrong application, regardless of the file type I send.
For example, this wants to open the calendar or settings for opening PDF files.

If I use the
Intent.setDataAndType()
the data is sent correctly to the correct application, but I get an
android.os.TransactionTooLargeException
exception on large data sets.

Any suggestion? Thank you.

EDIT:
Here's what I'm trying to achieve. I download a file from the network (txt, html, pdf...), I save the file locally and then I want to open/read that file within the device's default reader for that file type. If the user hasn't selected a reader for that file type the user will be prompt with the android default prompt to select an app that can read this file.
If the user does not have an app to read this file type, we just display a message saying the file cannot be opened on this device.

Answer

You still need to use setData() as FLAG_GRANT_READ_URI_PERMISSION only applies to the URI set with setData() or those added via setClipData() - note that the type is automatically provided for you by FileProvider.

As per the EXTRA_INTENT documentation, that extra must only contain an Intent object and is only used for ACTION_CHOOSER.