Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safeguard against "a matching Activity may not exist" in android settings

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 ?

like image 763
Mr_and_Mrs_D Avatar asked Nov 16 '13 11:11

Mr_and_Mrs_D


1 Answers

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.

like image 149
CommonsWare Avatar answered Oct 31 '22 02:10

CommonsWare