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?
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With