androidandroid-intentactivitynotfoundexception

No Activity found to handle Intent error with valid url


I have this small method:

private fun showWebsiteWithUrl(url: String) {
    val i = Intent(Intent.ACTION_VIEW)
    i.data = Uri.parse(url)
    startActivity(i)
}

And I see in google play that sometimes this method throw android.content.ActivityNotFoundException exception.

The url parameter is a valid url like this: http://www.stackoverflow.com/

This is the beginning of the stacktrace:

Caused by android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=http://wwww.stackoverflow.com/... }

I can't reproduce the issue on my phone, the user got this error on Huawei Y5 (DRA-L21) Android 8 and sometimes on Xiaomi devices with android 9.


Solution

  • You are using implicit intents to open a web link. It's possible that a user won't have any apps that handle the implicit intent you send to startActivity(). Or, an app may be inaccessible because of profile restrictions or settings put into place by an administrator. If that happens, the call fails and your app crashes. To verify that activity will receive the intent, call resolveActivity() on your Intent object. If the result is non-null, there is at least one app that can handle the intent and it's safe to call startActivity(). If the result is null, do not use the intent and, if possible, you should disable the feature that issues the intent. The following example shows how to verify that the intent resolves to an activity. This example doesn't use a URI, but the intent's data type is declared to specify the content carried by the extras.

    // Create the text message with a string
    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
    sendIntent.setType("text/plain");
    
    // Verify that the intent will resolve to an activity
    if (sendIntent.resolveActivity(getPackageManager()) != null) {
        startActivity(sendIntent);
    }