No Activity found to handle Intent error with valid url
Asked Answered
S

2

11

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.

Streamy answered 20/11, 2019 at 12:40 Comment(0)
B
9

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);
}
Barbie answered 20/11, 2019 at 12:59 Comment(1)
Thank you so much!Streamy
S
4

There are many scenarios in which this might happen, including:

  • The user is not the primary device owner, but rather is using a restricted profile, where that user does not have access to a Web browser

  • The user disabled all Web browser apps via Settings

  • The user is in some device-specific "family" mode where a Web browser happens to not be available

  • The Web browsers available to the user are no longer supporting plain HTTP for external links, preferring HTTPS

Never assume that you can start a third-party app, even for something as common as a Web browser. Always wrap startActivity() and startActivityForResult() calls that are bringing up third-party apps in a try/catch block and catch the ActivityNotFoundException.

Safier answered 20/11, 2019 at 12:57 Comment(1)
Thank you so much!Streamy

© 2022 - 2024 — McMap. All rights reserved.