Schor
Schor

Reputation: 141

How to force an url to be open in the device's browser when my app is set as the default app to open this url

I set my android app to open certain urls from a specific server. A situation may occur when my app is not meant to open a certain url, and so the server will return an error.

Once an error received, I would like to open this url in the device's browser. Since my app was set as the default app to open this kind of urls, trying to use:

Intent intent = new Intent(Intent.ACTION_VIEW, URI);
context.startActivity(intent);

Will cause the app to open recursively and endlessly since the device is recognizing the url as a url that needs to be open by my app.

One solution that I found is forcing the device to open the url in chrome:intent.setPackage("com.android.chrome");

A problem arises if the device does not contain the chrome app.

Is there an elegant solution rather then listing all the possible android browsers one by one?

P.S. the problematic urls do not have a common prefix that can distinguish them from the others.

Upvotes: 7

Views: 2809

Answers (1)

Schor
Schor

Reputation: 141

As CommonsWare suggested, I used PackageManger's queryIntentActivities() method to find the default browser:

Intent i = new Intent(Intent.ACTION_VIEW, unusedURI);
List<ResolveInfo> l = context.getPackageManager().queryIntentActivities(i, PackageManager.MATCH_DEFAULT_ONLY);

To extract the process name I used: l.get(0).activityInfo.processName:

intent.setPackage(l.get(0).activityInfo.processName);

Notice that it is also possible to receive all the matching apps by using the flag PackageManager.MATCH_ALL.

Upvotes: 6

Related Questions