Why use Intent.createChooser()?

2019-02-25 23:46发布

I found some code to send an email; it looks like this:

startActivity(Intent.createChooser(emailIntent, "Email"));

I changed it to:

startActivity(emailIntent);

And the result appears the same on my device. Why use Intent.createChooser()?

3条回答
爷的心禁止访问
2楼-- · 2019-02-26 00:22

It's useful when there is more than one mail client installed on the phone. The user gets to choose which one to use if you use intent.createChooser(...)

查看更多
Summer. ? 凉城
3楼-- · 2019-02-26 00:33

What you basically ask the system in the second statement is go find the Activity that can respond to the Intent "android.content.Intent.ACTION_SEND" and with the type set in the statement

emailIntent.setType("message/rfc822"); // or "text/plain"

but in the first statement you request the Android Application chooser to be displayed no matter if there is zero/one/or more than one Activity to handle the Intent.

Also, if you use the statement

startActivity(emailIntent);

And there is no email clients to respond to your intent (for example in the Emulator) then the App with throw "ActivityNotFoundException",but if you use:

startActivity(Intent.createChooser(emailIntent, "Email"));

And no email client is installed, then the App will display the error message "No Application can perform this action".

查看更多
趁早两清
4楼-- · 2019-02-26 00:39

Using the chooser forces the user to make a choice between the apps they have installed that satisfy the intent, regardless whether or not they have set one of them as a default. If the user has not set a default handler, they will get a chooser regardless whether or not you call createChooser. The only benefit I see to calling the chooser is that you get to put a name into the choice dialog rather than getting the default, "Complete action using" message.

IMHO, I think if the user wants to choose which app to use, they will not check the "always" button on the choice dialog they get by default and therefore the createChooser call should almost always be avoided.

查看更多
登录 后发表回答