Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 724
Schor Avatar asked Apr 16 '17 22:04

Schor


People also ask

How do I force a URL to open?

Quick MethodRight-click the link (on mac, use control+click), and select the option to copy the link. Open up a different web browser (Internet Explorer, Edge, Chrome, Firefox, Safari), and paste the copied link into the address bar of the alternative browser. Press Enter to go to the site.


1 Answers

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.

like image 73
Schor Avatar answered Oct 04 '22 20:10

Schor