Skip to content

Instantly share code, notes, and snippets.

@rocboronat
Last active July 21, 2016 15:58
Show Gist options
  • Save rocboronat/7cc2a24b23409e808099bd0ca84b5cde to your computer and use it in GitHub Desktop.
Save rocboronat/7cc2a24b23409e808099bd0ca84b5cde to your computer and use it in GitHub Desktop.
Use the more popular browser in the user's phone to open a URL
package com.fewlaps.quitnow;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import java.util.ArrayList;
import java.util.List;
public class PopularBrowser {
private static final String CHROME_PCKG = "com.android.chrome"; //>500M downloads
private static final String FIREFOX_PCKG = "org.mozilla.firefox"; //>100M downloads
private static final String OPERA_PCKG = "com.opera.browser"; //>50M downloads
private static final String UC_BROWSER_PCKG = "com.UCMobile.intl"; //>100M downloads, very geek
private static List<String> browsers;
static {
browsers = new ArrayList<>();
browsers.add(CHROME_PCKG);
browsers.add(FIREFOX_PCKG);
browsers.add(OPERA_PCKG);
browsers.add(UC_BROWSER_PCKG);
}
private final Context context;
public PopularBrowser(Context context) {
this.context = context;
}
public void open(String url) {
for (String browser : browsers) {
boolean hasBeenOpened = openWithBrowser(url, browser);
if (hasBeenOpened) {
return;
}
}
launchCommonAndroidChooser(url);
}
private boolean openWithBrowser(String url, String app) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setPackage(app);
context.startActivity(intent);
return true;
} catch (ActivityNotFoundException ex) {
return false;
}
}
private void launchCommonAndroidChooser(String url) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
context.startActivity(i);
}
}
@alorma
Copy link

alorma commented Jul 5, 2016

It's missing the ; in the package

package com.fewlaps.quitnow

@rocboronat
Copy link
Author

Thanks @alorma!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment