The majority of the Activity Actions (used to launch various Settings activities) in the Settings class come with a warning :
In some cases, a matching Activity may not exist, so ensure you safeguard against this.
So how do I safeguard against this ?
try {
final Intent i = new Intent(Settings. ACTION_WIRELESS_SETTINGS); // say
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // not sure if needed
startActivity(i);
} catch (Exception e) { // what should I catch here
// I would hate to catch Throwable, but should I ?
}
If I read this correctly for instance a runtime exception (NPE) is thrown. I would love to use something more specific though like ActivityNotFoundException
- but is it enough ?
If I read this correctly for instance a runtime exception (NPE) is thrown
No, that's some other problem. The Intent
clearly worked, as the crash is coming from Settings itself, not the app that called startActivity()
.
I would love to use something more specific though like ActivityNotFoundException - but is it enough ?
It should be.
If you are concerned about that, or would rather be proactive, rather than just calling startActivity()
, first use PackageManager
and resolveActivity()
. If that returns null
, there is no activity that matches the Intent
, and you should try something else.
来源:https://stackoverflow.com/questions/20018082/safeguard-against-a-matching-activity-may-not-exist-in-android-settings