What is the purpose of using Intent.createChooser(

2020-02-09 06:41发布

问题:

When ever we need to send an email in Android we will invoke registered email application using Intent.ACTION_SEND like below

Intent i = new Intent(Intent.ACTION_SEND);
startActivity(Intent.createChooser(i, "Send mail..."));

My doubt is why do we need to use Intent.createChooser in startActivity rather than using startActivty(i). Is there any specific reason of using Intent.createChooser()?

回答1:

AFAIK, if you use Intent.createChooser, there are three differences:

  1. You can specify the title of the chooser dialog to make it more clear.

  2. The system will always present the chooser dialog even if the user has chosen a default one.

  3. If your intent created by Intent.createChooser doesn't match any activity, the system will still present a dialog with the specified title and an error message No application can perform this action. Or for the normal intent, you may get an Android runtime error with: Caused by: android.content.ActivityNotFoundException: No Activity found to handle Intent



回答2:

The chooser enables the user to pick another mail application than the default. Its very useful if you use normal gmail (privat) and email (work related) and you want to choose which one to take.

Should always be used...



回答3:

Way old message but for others who come across it, you can set the type on the Intent to the mime type of emails, which will at least limit it to applications that can send that appropriate type of message:

Intent i = new Intent(Intent.ACTION_SEND); 
i.setType( "message/rfc822");
startActivity(Intent.createChooser(i, "Send mail..."));

Makes the chooser dialog much cleaner.



回答4:

If you don't use createChooser(), the system will still present the chooser dialog unless the user has already expressed their decision as to which installed program to use for the given task (or they have withdrawn their previous decision).

If you do use createChooser(), the system will always present the dialog, even if there already is an expressed preference.

So, both are absolutely correct, you have to decide which one to use in any given case. Your mileage might vary, but basically, if you offer up a format like a text, an image, a video or similar for display or editing, you probably want to omit createChooser() so that whatever the user already prefers can start immediately. On the other hand, if you want to share something that you expect the user to handle with a different installed program (say, send an e-mail, Facebook, chat, whatever) every time, you probably want to use createChooser() to make it easy for your user to select on the fly.



回答5:

I personally use:

try {
    startActivity(i);
} catch (ActivityNotFoundException e) {
    startActivity(Intent.createChooser(i, null));
}

So it will use default if user has default, will popup "no app" window if no app. Both are happy.