Search code examples
android

Opening link using Intent.ACTION_VIEW caused android.content.ActivityNotFoundException on certain device(s)


Recently I started getting android.content.ActivityNotFoundException: for my app logged on Google Play Console. Codes causing this exception are :

private void openLink(String url) {
    Uri uri = Uri.parse(url); 
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
}

Now the exception is rarely happened, it works fine on most of devices, and the url is 100% valid (a link to https://mathsolver.microsoft.com/).

My question is what caused them and what is the best way to handle them.

Is a simple try catch enough or there is way so that user that catch this exception can still open the url from their phone?


Solution

  • Whenever you are starting an activity that is from another app — such as a Web browser — you have to take into account that the user might not have access to such an app. Even something as common as a Web browser might be restricted on some devices (e.g., devices used by children).

    As such, you need to wrap such startActivity() calls in a try/catch block and deal with ActivityNotFoundException. Exactly how you deal with it will be up to your app, but you will need to explain to the user that you are unable to start the desired app for some reason.