如何从内置web浏览器而不是应用程序中的代码打开URL?
我试过了:
try {
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(download_link));
startActivity(myIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No application can handle this request."
+ " Please install a webbrowser", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
但我有个例外:
No activity found to handle Intent{action=android.intent.action.VIEW data =www.google.com
简单和最佳实践
方法1:
String intentUrl="www.google.com";
Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(intentUrl));
if(webIntent.resolveActivity(getPackageManager())!=null){
startActivity(webIntent);
}else{
/*show Error Toast
or
Open play store to download browser*/
}
方法2:
try{
String intentUrl="www.google.com";
Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(intentUrl));
startActivity(webIntent);
}catch (ActivityNotFoundException e){
/*show Error Toast
or
Open play store to download browser*/
}
//OnClick侦听器
@Override
public void onClick(View v) {
String webUrl = news.getNewsURL();
if(webUrl!="")
Utils.intentWebURL(mContext, webUrl);
}
//你的Util方法
public static void intentWebURL(Context context, String url) {
if (!url.startsWith("http://") && !url.startsWith("https://")) {
url = "http://" + url;
}
boolean flag = isURL(url);
if (flag) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(url));
context.startActivity(browserIntent);
}
}