如何从我的应用程序在 Android 的网络浏览器中打开 URL?

发布于 2024-08-19 23:00:34 字数 610 浏览 9 评论 0原文

如何从内置 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

How to open a URL from code in the built-in web browser rather than within my application?

I tried this:

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();
}

but I got an Exception:

No activity found to handle Intent{action=android.intent.action.VIEW data =www.google.com

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

Oo萌小芽oO 2024-08-26 23:00:34

试试这个:

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);

这对我来说效果很好。

至于缺少的“http://”,我只会做这样的事情:

if (!url.startsWith("http://") && !url.startsWith("https://"))
   url = "http://" + url;

我也可能会预先填充用户在其中输入“http://”的 URL 的 EditText。


在科特林中:

if (!url.startsWith("http://") && !url.startsWith("https://")) {
    url = "http://$url"
}

val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(browserIntent)

Try this:

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);

That works fine for me.

As for the missing "http://" I'd just do something like this:

if (!url.startsWith("http://") && !url.startsWith("https://"))
   url = "http://" + url;

I would also probably pre-populate your EditText that the user is typing a URL in with "http://".


In Kotlin:

if (!url.startsWith("http://") && !url.startsWith("https://")) {
    url = "http://$url"
}

val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(browserIntent)
与风相奔跑 2024-08-26 23:00:34

实现此目的的常见方法是使用下一个代码:

String url = "http://www.stackoverflow.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url)); 
startActivity(i); 

可以将其更改为短代码版本......

Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.stackoverflow.com"));      
startActivity(intent); 

或者:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com")); 
startActivity(intent);

最短! :

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com")));

A common way to achieve this is with the next code:

String url = "http://www.stackoverflow.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url)); 
startActivity(i); 

that could be changed to a short code version ...

Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.stackoverflow.com"));      
startActivity(intent); 

or :

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com")); 
startActivity(intent);

the shortest! :

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.stackoverflow.com")));
醉梦枕江山 2024-08-26 23:00:34

简单答案

您可以查看Android Developer 的官方示例

/**
 * Open a web page of a specified URL
 *
 * @param url URL to open
 */
public void openWebPage(String url) {
    Uri webpage = Uri.parse(url);
    Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

它是如何工作的

请查看 Intent 的构造函数

public Intent (String action, Uri uri)

您可以将 android.net.Uri 实例传递给第二个参数,并根据给定的数据 url 创建一个新的 Intent。

然后,只需调用 startActivity(Intent Intent) 即可启动一个新的 Activity,该 Activity 与具有给定 URL 的 Intent 捆绑在一起。

我需要 if 检查语句吗?

是的。 docs 说:

如果设备上没有可以接收隐式意图的应用程序,您的应用程序将在调用 startActivity() 时崩溃。要首先验证是否存在可以接收意图的应用程序,请在您的意图对象上调用resolveActivity()。如果结果非空,则至少有一个应用程序可以处理该意图,并且可以安全地调用 startActivity()。如果结果为空,则不应使用该意图,并且如果可能,应禁用调用该意图的功能。

额外的好处

你可以在创建 Intent 实例时写一行,如下所示:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

Simple Answer

You can see the official sample from Android Developer.

/**
 * Open a web page of a specified URL
 *
 * @param url URL to open
 */
public void openWebPage(String url) {
    Uri webpage = Uri.parse(url);
    Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

How it works

Please have a look at the constructor of Intent:

public Intent (String action, Uri uri)

You can pass android.net.Uri instance to the 2nd parameter, and a new Intent is created based on the given data url.

And then, simply call startActivity(Intent intent) to start a new Activity, which is bundled with the Intent with the given URL.

Do I need the if check statement?

Yes. The docs says:

If there are no apps on the device that can receive the implicit intent, your app will crash when it calls startActivity(). To first verify that an app exists to 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, you should not use the intent and, if possible, you should disable the feature that invokes the intent.

Bonus

You can write in one line when creating the Intent instance like below:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
仅冇旳回忆 2024-08-26 23:00:34

在 2.3 中,我的运气更好,

final Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(url));
activity.startActivity(intent);

区别在于使用 Intent.ACTION_VIEW 而不是字符串 "android.intent.action.VIEW"

In 2.3, I had better luck with

final Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(url));
activity.startActivity(intent);

The difference being the use of Intent.ACTION_VIEW rather than the String "android.intent.action.VIEW"

我早已燃尽 2024-08-26 23:00:34

Kotlin 答案:

val browserIntent = Intent(Intent.ACTION_VIEW, uri)
ContextCompat.startActivity(context, browserIntent, null)

我在 Uri 上添加了一个扩展,使这变得更加容易

myUri.openInBrowser(context)

fun Uri?.openInBrowser(context: Context) {
    this ?: return // Do nothing if uri is null

    val browserIntent = Intent(Intent.ACTION_VIEW, this)
    ContextCompat.startActivity(context, browserIntent, null)
}

作为奖励,这里有一个简单的扩展函数,可以安全地将字符串转换为 Uri。

"https://stackoverflow.com".asUri()?.openInBrowser(context)

fun String?.asUri(): Uri? {
    return try {
        Uri.parse(this)
    } catch (e: Exception) {
        null
    }
}

The Kotlin answer:

val browserIntent = Intent(Intent.ACTION_VIEW, uri)
ContextCompat.startActivity(context, browserIntent, null)

I have added an extension on Uri to make this even easier

myUri.openInBrowser(context)

fun Uri?.openInBrowser(context: Context) {
    this ?: return // Do nothing if uri is null

    val browserIntent = Intent(Intent.ACTION_VIEW, this)
    ContextCompat.startActivity(context, browserIntent, null)
}

As a bonus, here is a simple extension function to safely convert a String to Uri.

"https://stackoverflow.com".asUri()?.openInBrowser(context)

fun String?.asUri(): Uri? {
    return try {
        Uri.parse(this)
    } catch (e: Exception) {
        null
    }
}
一抹苦笑 2024-08-26 23:00:34

试试这个:

Uri uri = Uri.parse("https://www.google.com");
startActivity(new Intent(Intent.ACTION_VIEW, uri));

或者如果你想在你的活动中打开网络浏览器,然后这样做:

WebView webView = (WebView) findViewById(R.id.webView1);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webView.loadUrl(URL);

如果你想在浏览器中使用缩放控制,那么你可以使用:

settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);

Try this:

Uri uri = Uri.parse("https://www.google.com");
startActivity(new Intent(Intent.ACTION_VIEW, uri));

or if you want then web browser open in your activity then do like this:

WebView webView = (WebView) findViewById(R.id.webView1);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webView.loadUrl(URL);

and if you want to use zoom control in your browser then you can use:

settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
(り薆情海 2024-08-26 23:00:34

如果您想向用户显示与所有浏览器列表的对话,以便他可以选择首选,这里是示例代码:

private static final String HTTPS = "https://";
private static final String HTTP = "http://";

public static void openBrowser(final Context context, String url) {

     if (!url.startsWith(HTTP) && !url.startsWith(HTTPS)) {
            url = HTTP + url;
     }

     Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
     context.startActivity(Intent.createChooser(intent, "Choose browser"));// Choose browser is arbitrary :)

}

If you want to show user a dialogue with all browser list, so he can choose preferred, here is sample code:

private static final String HTTPS = "https://";
private static final String HTTP = "http://";

public static void openBrowser(final Context context, String url) {

     if (!url.startsWith(HTTP) && !url.startsWith(HTTPS)) {
            url = HTTP + url;
     }

     Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
     context.startActivity(Intent.createChooser(intent, "Choose browser"));// Choose browser is arbitrary :)

}
甜点 2024-08-26 23:00:34

就像其他人写的解决方案(工作正常)一样,我想回答同样的问题,但有一个我认为大多数人更喜欢使用的提示。

如果您希望在新任务中开始打开应用程序,独立于您自己的应用程序,而不是停留在同一堆栈上,您可以使用以下代码:

final Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY|Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET|Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
startActivity(intent);

还有一种方法可以在 Chrome 自定义标签 。 Kotlin 中的示例:

@JvmStatic
fun openWebsite(activity: Activity, websiteUrl: String, useWebBrowserAppAsFallbackIfPossible: Boolean) {
    var websiteUrl = websiteUrl
    if (TextUtils.isEmpty(websiteUrl))
        return
    if (websiteUrl.startsWith("www"))
        websiteUrl = "http://$websiteUrl"
    else if (!websiteUrl.startsWith("http"))
        websiteUrl = "http://www.$websiteUrl"
    val finalWebsiteUrl = websiteUrl
    //https://github.com/GoogleChrome/custom-tabs-client
    val webviewFallback = object : CustomTabActivityHelper.CustomTabFallback {
        override fun openUri(activity: Activity, uri: Uri?) {
            var intent: Intent
            if (useWebBrowserAppAsFallbackIfPossible) {
                intent = Intent(Intent.ACTION_VIEW, Uri.parse(finalWebsiteUrl))
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_HISTORY
                        or Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
                if (!CollectionUtil.isEmpty(activity.packageManager.queryIntentActivities(intent, 0))) {
                    activity.startActivity(intent)
                    return
                }
            }
            // open our own Activity to show the URL
            intent = Intent(activity, WebViewActivity::class.java)
            WebViewActivity.prepareIntent(intent, finalWebsiteUrl)
            activity.startActivity(intent)
        }
    }
    val uri = Uri.parse(finalWebsiteUrl)
    val intentBuilder = CustomTabsIntent.Builder()
    val customTabsIntent = intentBuilder.build()
    customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_HISTORY
            or Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
    CustomTabActivityHelper.openCustomTab(activity, customTabsIntent, uri, webviewFallback)
}

Just like the solutions other have written (that work fine), I would like to answer the same thing, but with a tip that I think most would prefer to use.

In case you wish the app you start to open in a new task, indepandant of your own, instead of staying on the same stack, you can use this code:

final Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY|Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET|Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
startActivity(intent);

There is also a way to open the URL in Chrome Custom Tabs . Example in Kotlin :

@JvmStatic
fun openWebsite(activity: Activity, websiteUrl: String, useWebBrowserAppAsFallbackIfPossible: Boolean) {
    var websiteUrl = websiteUrl
    if (TextUtils.isEmpty(websiteUrl))
        return
    if (websiteUrl.startsWith("www"))
        websiteUrl = "http://$websiteUrl"
    else if (!websiteUrl.startsWith("http"))
        websiteUrl = "http://www.$websiteUrl"
    val finalWebsiteUrl = websiteUrl
    //https://github.com/GoogleChrome/custom-tabs-client
    val webviewFallback = object : CustomTabActivityHelper.CustomTabFallback {
        override fun openUri(activity: Activity, uri: Uri?) {
            var intent: Intent
            if (useWebBrowserAppAsFallbackIfPossible) {
                intent = Intent(Intent.ACTION_VIEW, Uri.parse(finalWebsiteUrl))
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_HISTORY
                        or Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
                if (!CollectionUtil.isEmpty(activity.packageManager.queryIntentActivities(intent, 0))) {
                    activity.startActivity(intent)
                    return
                }
            }
            // open our own Activity to show the URL
            intent = Intent(activity, WebViewActivity::class.java)
            WebViewActivity.prepareIntent(intent, finalWebsiteUrl)
            activity.startActivity(intent)
        }
    }
    val uri = Uri.parse(finalWebsiteUrl)
    val intentBuilder = CustomTabsIntent.Builder()
    val customTabsIntent = intentBuilder.build()
    customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_HISTORY
            or Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
    CustomTabActivityHelper.openCustomTab(activity, customTabsIntent, uri, webviewFallback)
}
三生殊途 2024-08-26 23:00:34

使用 Webview 在同一应用程序中加载 URL 中的其他选项

webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");

other option In Load Url in Same Application using Webview

webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.com");
荆棘i 2024-08-26 23:00:34

您也可以这样

在 xml 中:

<?xml version="1.0" encoding="utf-8"?>
<WebView  
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

在 java 代码中:

public class WebViewActivity extends Activity {

private WebView webView;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);

    webView = (WebView) findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl("http://www.google.com");

 }

}

在 Manifest 中不要忘记添加互联网权限...

You can also go this way

In xml :

<?xml version="1.0" encoding="utf-8"?>
<WebView  
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

In java code :

public class WebViewActivity extends Activity {

private WebView webView;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);

    webView = (WebView) findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl("http://www.google.com");

 }

}

In Manifest dont forget to add internet permission...

め可乐爱微笑 2024-08-26 23:00:34

所以我已经找了很长时间了,因为所有其他答案都是打开该链接的默认应用程序,而不是默认浏览器,这就是我想要的。

我终于成功做到了:

// gathering the default browser
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://"));
final ResolveInfo resolveInfo = context.getPackageManager()
    .resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
String defaultBrowserPackageName = resolveInfo.activityInfo.packageName;


final Intent intent2 = new Intent(Intent.ACTION_VIEW);
intent2.setData(Uri.parse(url));

if (!defaultBrowserPackageName.equals("android")) {
    // android = no default browser is set 
    // (android < 6 or fresh browser install or simply no default set)
    // if it's the case (not in this block), it will just use normal way.
    intent2.setPackage(defaultBrowserPackageName);
}

context.startActivity(intent2);

顺便说一句,您可以注意到 context。无论如何,因为我已将其用于静态 util 方法,如果您在活动中执行此操作,则不需要它。

So I've looked for this for a long time because all the other answers were opening default app for that link, but not default browser and that's what I wanted.

I finally managed to do so:

// gathering the default browser
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://"));
final ResolveInfo resolveInfo = context.getPackageManager()
    .resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
String defaultBrowserPackageName = resolveInfo.activityInfo.packageName;


final Intent intent2 = new Intent(Intent.ACTION_VIEW);
intent2.setData(Uri.parse(url));

if (!defaultBrowserPackageName.equals("android")) {
    // android = no default browser is set 
    // (android < 6 or fresh browser install or simply no default set)
    // if it's the case (not in this block), it will just use normal way.
    intent2.setPackage(defaultBrowserPackageName);
}

context.startActivity(intent2);

BTW, you can notice context.whatever, because I've used this for a static util method, if you are doing this in an activity, it's not needed.

浪菊怪哟 2024-08-26 23:00:34

Webview 可用于在应用程序中加载 Url。
URL 可以由用户在文本视图中提供,也可以对其进行硬编码。

另外不要忘记 AndroidManifest.xml 中的互联网权限。

String url="http://developer.android.com/index.html"

WebView wv=(WebView)findViewById(R.id.webView);
wv.setWebViewClient(new MyBrowser());
wv.getSettings().setLoadsImagesAutomatically(true);
wv.getSettings().setJavaScriptEnabled(true);
wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv.loadUrl(url);

private class MyBrowser extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

Webview can be used to load Url in your applicaion.
URL can be provided from user in text view or you can hardcode it.

Also don't forget internet permissions in AndroidManifest.

String url="http://developer.android.com/index.html"

WebView wv=(WebView)findViewById(R.id.webView);
wv.setWebViewClient(new MyBrowser());
wv.getSettings().setLoadsImagesAutomatically(true);
wv.getSettings().setJavaScriptEnabled(true);
wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv.loadUrl(url);

private class MyBrowser extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}
°如果伤别离去 2024-08-26 23:00:34

在您的 try 块中,粘贴以下代码,Android Intent 直接使用 URI(统一资源标识符)大括号内的链接来识别链接的位置。

你可以试试这个:

Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(myIntent);

Within in your try block,paste the following code,Android Intent uses directly the link within the URI(Uniform Resource Identifier) braces in order to identify the location of your link.

You can try this:

Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(myIntent);
挖鼻大婶 2024-08-26 23:00:34

短代码版本...

 if (!strUrl.startsWith("http://") && !strUrl.startsWith("https://")){
     strUrl= "http://" + strUrl;
 }


 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(strUrl)));

A short code version...

 if (!strUrl.startsWith("http://") && !strUrl.startsWith("https://")){
     strUrl= "http://" + strUrl;
 }


 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(strUrl)));
盛夏尉蓝 2024-08-26 23:00:34

简单且最佳实践

方法 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*/
    }

Simple and Best Practice

Method 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*/
            }

Method 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*/
    }
べ繥欢鉨o。 2024-08-26 23:00:34

短&可爱的 Kotlin 辅助函数:

private fun openUrl(link: String) =
    startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(link)))

Short & sweet Kotlin helper function:

private fun openUrl(link: String) =
    startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(link)))
醉殇 2024-08-26 23:00:34
String url = "http://www.example.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
String url = "http://www.example.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
节枝 2024-08-26 23:00:34

Chrome 自定义选项卡现已可用:

第一步是将自定义选项卡支持库添加到您的 build.gradle 文件中:

dependencies {
    ...
    compile 'com.android.support:customtabs:24.2.0'
}

然后,打开 Chrome 自定义选项卡:

String url = "https://www.google.pt/";
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse(url));

了解更多信息:
https://developer.chrome.com/multidevice/android/customtabs

Chrome custom tabs are now available:

The first step is adding the Custom Tabs Support Library to your build.gradle file:

dependencies {
    ...
    compile 'com.android.support:customtabs:24.2.0'
}

And then, to open a chrome custom tab:

String url = "https://www.google.pt/";
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse(url));

For more info:
https://developer.chrome.com/multidevice/android/customtabs

单调的奢华 2024-08-26 23:00:34

简单,通过意图查看网站,

Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse("http://www.yoursite.in"));
startActivity(viewIntent);  

使用这个简单的代码在 Android 应用程序中查看您的网站。

在清单文件中添加互联网权限,

<uses-permission android:name="android.permission.INTERNET" /> 

Simple, website view via intent,

Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse("http://www.yoursite.in"));
startActivity(viewIntent);  

use this simple code toview your website in android app.

Add internet permission in manifest file,

<uses-permission android:name="android.permission.INTERNET" /> 
空心空情空意 2024-08-26 23:00:34

在 Android 11 中从 URL 打开链接的一种新的更好方法。

  try {
        val intent = Intent(ACTION_VIEW, Uri.parse(url)).apply {
            // The URL should either launch directly in a non-browser app
            // (if it’s the default), or in the disambiguation dialog
            addCategory(CATEGORY_BROWSABLE)
            flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_REQUIRE_NON_BROWSER or
                    FLAG_ACTIVITY_REQUIRE_DEFAULT
        }
        startActivity(intent)
    } catch (e: ActivityNotFoundException) {
        // Only browser apps are available, or a browser is the default app for this intent
        // This code executes in one of the following cases:
        // 1. Only browser apps can handle the intent.
        // 2. The user has set a browser app as the default app.
        // 3. The user hasn't set any app as the default for handling this URL.
        openInCustomTabs(url)
    }

参考:

https://medium.com/androiddevelopers/package-visibility-in-android-11-cc857f221cd9https://developer.android.com/training/package-visibility/use-cases#avoid-a-disambiguation-dialog

A new and better way to open link from URL in Android 11.

  try {
        val intent = Intent(ACTION_VIEW, Uri.parse(url)).apply {
            // The URL should either launch directly in a non-browser app
            // (if it’s the default), or in the disambiguation dialog
            addCategory(CATEGORY_BROWSABLE)
            flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_REQUIRE_NON_BROWSER or
                    FLAG_ACTIVITY_REQUIRE_DEFAULT
        }
        startActivity(intent)
    } catch (e: ActivityNotFoundException) {
        // Only browser apps are available, or a browser is the default app for this intent
        // This code executes in one of the following cases:
        // 1. Only browser apps can handle the intent.
        // 2. The user has set a browser app as the default app.
        // 3. The user hasn't set any app as the default for handling this URL.
        openInCustomTabs(url)
    }

References:

https://medium.com/androiddevelopers/package-visibility-in-android-11-cc857f221cd9 and https://developer.android.com/training/package-visibility/use-cases#avoid-a-disambiguation-dialog

云淡月浅 2024-08-26 23:00:34
Intent getWebPage = new Intent(Intent.ACTION_VIEW, Uri.parse(MyLink));          
startActivity(getWebPage);
Intent getWebPage = new Intent(Intent.ACTION_VIEW, Uri.parse(MyLink));          
startActivity(getWebPage);
吹泡泡o 2024-08-26 23:00:34

MarkB 的回应是正确的。就我而言,我使用的是 Xamarin,与 C# 和 Xamarin 一起使用的代码是:

var uri = Android.Net.Uri.Parse ("http://www.xamarin.com");
var intent = new Intent (Intent.ActionView, uri);
StartActivity (intent);

此信息取自: https://developer.xamarin.com/recipes/android/fundamentals/intent/open_a_webpage_in_the_browser_application/

The response of MarkB is right. In my case I'm using Xamarin, and the code to use with C# and Xamarin is:

var uri = Android.Net.Uri.Parse ("http://www.xamarin.com");
var intent = new Intent (Intent.ActionView, uri);
StartActivity (intent);

This information is taked from: https://developer.xamarin.com/recipes/android/fundamentals/intent/open_a_webpage_in_the_browser_application/

メ斷腸人バ 2024-08-26 23:00:34

基于 Mark B 的回答和以下评论:

protected void launchUrl(String url) {
    Uri uri = Uri.parse(url);

    if (uri.getScheme() == null || uri.getScheme().isEmpty()) {
        uri = Uri.parse("http://" + url);
    }

    Intent browserIntent = new Intent(Intent.ACTION_VIEW, uri);

    if (browserIntent.resolveActivity(getPackageManager()) != null) {
        startActivity(browserIntent);
    }
}

Based on the answer by Mark B and the comments bellow:

protected void launchUrl(String url) {
    Uri uri = Uri.parse(url);

    if (uri.getScheme() == null || uri.getScheme().isEmpty()) {
        uri = Uri.parse("http://" + url);
    }

    Intent browserIntent = new Intent(Intent.ACTION_VIEW, uri);

    if (browserIntent.resolveActivity(getPackageManager()) != null) {
        startActivity(browserIntent);
    }
}
梦醒时光 2024-08-26 23:00:34

这种方式使用了一种方法,允许您输入任何字符串,而不是固定输入。如果重复使用多次,这确实可以节省一些代码行,因为您只需要三行来调用该方法。

public Intent getWebIntent(String url) {
    //Make sure it is a valid URL before parsing the URL.
    if(!url.contains("http://") && !url.contains("https://")){
        //If it isn't, just add the HTTP protocol at the start of the URL.
        url = "http://" + url;
    }
    //create the intent
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)/*And parse the valid URL. It doesn't need to be changed at this point, it we don't create an instance for it*/);
    if (intent.resolveActivity(getPackageManager()) != null) {
        //Make sure there is an app to handle this intent
        return intent;
    }
    //If there is no app, return null.
    return null;
}

使用这种方法使其具有普遍用途。 IT 不必放置在特定的活动中,因为您可以像这样使用它:

Intent i = getWebIntent("google.com");
if(i != null)
    startActivity();

或者如果您想在活动之外启动它,您只需在活动实例上调用 startActivity 即可:

Intent i = getWebIntent("google.com");
if(i != null)
    activityInstance.startActivity(i);

如这两个代码块所示是一个空检查。这是因为如果没有应用程序来处理意图,它会返回 null。

如果没有定义协议,此方法默认为 HTTP,因为有些网站没有 SSL 证书(HTTPS 连接所需的证书),如果您尝试使用 HTTPS 但不存在,这些网站将停止工作。任何网站仍然可以强制转换为 HTTPS,因此无论哪种方式,这些网站都会让您进入 HTTPS。


因为此方法使用外部资源来显示页面,所以您无需声明 Internet 权限。显示网页的应用程序必须执行此操作

This way uses a method, to allow you to input any String instead of having a fixed input. This does save some lines of code if used a repeated amount of times, as you only need three lines to call the method.

public Intent getWebIntent(String url) {
    //Make sure it is a valid URL before parsing the URL.
    if(!url.contains("http://") && !url.contains("https://")){
        //If it isn't, just add the HTTP protocol at the start of the URL.
        url = "http://" + url;
    }
    //create the intent
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)/*And parse the valid URL. It doesn't need to be changed at this point, it we don't create an instance for it*/);
    if (intent.resolveActivity(getPackageManager()) != null) {
        //Make sure there is an app to handle this intent
        return intent;
    }
    //If there is no app, return null.
    return null;
}

Using this method makes it universally usable. IT doesn't have to be placed in a specific activity, as you can use it like this:

Intent i = getWebIntent("google.com");
if(i != null)
    startActivity();

Or if you want to start it outside an activity, you simply call startActivity on the activity instance:

Intent i = getWebIntent("google.com");
if(i != null)
    activityInstance.startActivity(i);

As seen in both of these code blocks there is a null-check. This is as it returns null if there is no app to handle the intent.

This method defaults to HTTP if there is no protocol defined, as there are websites who don't have an SSL certificate(what you need for an HTTPS connection) and those will stop working if you attempt to use HTTPS and it isn't there. Any website can still force over to HTTPS, so those sides lands you at HTTPS either way


Because this method uses outside resources to display the page, there is no need for you to declare the INternet permission. The app that displays the webpage has to do that

你的背包 2024-08-26 23:00:34

android.webkit.URLUtil 具有方法 guessUrl(String) 工作得很好(即使使用 file://data ://)自 Api 级别 1 (Android 1.0) 起。用作:

String url = URLUtil.guessUrl(link);

// url.com            ->  http://url.com/     (adds http://)
// http://url         ->  http://url.com/     (adds .com)
// https://url        ->  https://url.com/    (adds .com)
// url                ->  http://www.url.com/ (adds http://www. and .com)
// http://www.url.com ->  http://www.url.com/ 
// https://url.com    ->  https://url.com/
// file://dir/to/file ->  file://dir/to/file
// data://dataline    ->  data://dataline
// content://test     ->  content://test

在 Activity 调用中:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(URLUtil.guessUrl(download_link)));

if (intent.resolveActivity(getPackageManager()) != null)
    startActivity(intent);

检查完整的 guessUrl 代码 了解更多信息。

android.webkit.URLUtil has the method guessUrl(String) working perfectly fine (even with file:// or data://) since Api level 1 (Android 1.0). Use as:

String url = URLUtil.guessUrl(link);

// url.com            ->  http://url.com/     (adds http://)
// http://url         ->  http://url.com/     (adds .com)
// https://url        ->  https://url.com/    (adds .com)
// url                ->  http://www.url.com/ (adds http://www. and .com)
// http://www.url.com ->  http://www.url.com/ 
// https://url.com    ->  https://url.com/
// file://dir/to/file ->  file://dir/to/file
// data://dataline    ->  data://dataline
// content://test     ->  content://test

In the Activity call:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(URLUtil.guessUrl(download_link)));

if (intent.resolveActivity(getPackageManager()) != null)
    startActivity(intent);

Check the complete guessUrl code for more info.

赏烟花じ飞满天 2024-08-26 23:00:34
String url = "https://www.thandroid-mania.com/";
if (url.startsWith("https://") || url.startsWith("http://")) {
    Uri uri = Uri.parse(url);
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
}else{
    Toast.makeText(mContext, "Invalid Url", Toast.LENGTH_SHORT).show();
}

该错误是由于 URL 无效而发生的,Android 操作系统无法找到您的数据的操作视图。所以您必须验证 URL 是否有效。

String url = "https://www.thandroid-mania.com/";
if (url.startsWith("https://") || url.startsWith("http://")) {
    Uri uri = Uri.parse(url);
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
}else{
    Toast.makeText(mContext, "Invalid Url", Toast.LENGTH_SHORT).show();
}

That error occurred because of invalid URL, Android OS can't find action view for your data. So you have validate that the URL is valid or not.

对你的占有欲 2024-08-26 23:00:34

科特林

startActivity(Intent(Intent.ACTION_VIEW).apply {
            data = Uri.parse(your_link)
        })

Kotlin

startActivity(Intent(Intent.ACTION_VIEW).apply {
            data = Uri.parse(your_link)
        })
十年九夏 2024-08-26 23:00:34

我检查了每个答案,但是哪个应用程序具有与用户想要使用的相同 URL 的深度链接?

今天我收到这个案例,答案是 browserIntent.setPackage("browser_package_name");

例如:

   Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
    browserIntent.setPackage("com.android.chrome"); // Whatever browser you are using
    startActivity(browserIntent);

I checked every answer but what app has deeplinking with same URL that user want to use?

Today I got this case and answer is browserIntent.setPackage("browser_package_name");

e.g. :

   Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
    browserIntent.setPackage("com.android.chrome"); // Whatever browser you are using
    startActivity(browserIntent);
伴随着你 2024-08-26 23:00:34

Jetpack Compose

如果您使用 jetpack compose,则需要首先获取可组合函数的上下文

val localContext = LocalContext.current
val browseIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://google.com"))
startActivity(localContext, browseIntent, null)

Jetpack Compose

If you are using jetpack compose, you need to get the context of your composable function first

val localContext = LocalContext.current
val browseIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://google.com"))
startActivity(localContext, browseIntent, null)
巷子口的你 2024-08-26 23:00:34

我认为这是最好的

openBrowser(context, "http://www.google.com")

将下面的代码放入全局类中

    public static void openBrowser(Context context, String url) {

        if (!url.startsWith("http://") && !url.startsWith("https://"))
            url = "http://" + url;

        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        context.startActivity(browserIntent);
    }

I think this is the best

openBrowser(context, "http://www.google.com")

Put below code into global class

    public static void openBrowser(Context context, String url) {

        if (!url.startsWith("http://") && !url.startsWith("https://"))
            url = "http://" + url;

        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        context.startActivity(browserIntent);
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文