Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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?

like image 773
ewin.str Avatar asked Feb 23 '26 15:02

ewin.str


2 Answers

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.

like image 146
CommonsWare Avatar answered Feb 27 '26 03:02

CommonsWare


This exception is thrown when a call to Context#startActivity or one of its variants fails because an Activity can not be found to execute the given Intent

When you are trying to open a file and get this Exception it means that even the system doesnt have the appropriate application to handle it or, as @CommonsWare said maybe the user doesnt have given the appropriate permissions.

This how I handle this exception hopes it help you:

    Intent intent;

    intent = new Intent(Intent.ACTION_VIEW);

    // Add flags to grant URI permissions
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    try {
        startActivity(intent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(LinkFilesActivity.this, "No application to handle this file type", Toast.LENGTH_SHORT).show();
    }
like image 25
Chris Damianidis Avatar answered Feb 27 '26 01:02

Chris Damianidis