简体   繁体   English

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

[英]How can I open a URL in Android's web browser from my application?

How to open an URL from code in the built-in web browser rather than within my application?如何从内置 web 浏览器中的代码而不是在我的应用程序中打开 URL?

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

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:至于缺少的“http://”,我只会做这样的事情:

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://".我也可能会预先填充用户正在使用“http://”键入 URL 的 EditText。

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")));

happy coding!快乐编码!

Simple Answer简单的答案

You can see the official sample from Android Developer .您可以查看来自 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 :请看一下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.您可以将android.net.Uri实例传递给第二个参数,并根据给定的数据 url 创建一个新的 Intent。

And then, simply call startActivity(Intent intent) to start a new Activity, which is bundled with the Intent with the given URL.然后,只需调用startActivity(Intent intent)即可启动一个新的 Activity,该 Activity 与具有给定 URL 的 Intent 捆绑在一起。

Do I need the if check statement?我需要if check 语句吗?

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().如果设备上没有可以接收隐式意图的应用程序,您的应用程序将在调用 startActivity() 时崩溃。 To first verify that an app exists to receive the intent, call resolveActivity() on your Intent object.要首先验证应用程序是否存在以接收 Intent,请在您的 Intent 对象上调用 resolveActivity()。 If the result is non-null, there is at least one app that can handle the intent and it's safe to call startActivity().如果结果不为空,则至少有一个应用程序可以处理该意图,并且调用 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 intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

In 2.3, I had better luck with在 2.3 中,我有更好的运气

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"不同之处在于使用Intent.ACTION_VIEW而不是字符串"android.intent.action.VIEW"

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

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 :)

}

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 .还有一种方法可以在Chrome Custom Tabs 中打开 URL。 Example in Kotlin : 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)
}

other option In Load Url in Same Application using Webview使用 Webview 在同一应用程序中加载 URL 中的其他选项

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

You can also go this way你也可以这样走

In xml :在 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 :在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");

 }

}

In Manifest dont forget to add internet permission...在清单中不要忘记添加互联网权限...

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我在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)
}

As a bonus, here is a simple extension function to safely convert a String to Uri.作为奖励,这里有一个简单的扩展函数,可以安全地将字符串转换为 Uri。

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

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

Webview can be used to load Url in your applicaion. Webview 可用于在您的应用程序中加载 Url。 URL can be provided from user in text view or you can hardcode it. URL 可以在文本视图中由用户提供,也可以硬编码。

Also don't forget internet permissions in AndroidManifest.也不要忘记 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;
    }
}

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.在您的 try 块中,粘贴以下代码,Android Intent 直接使用 URI(统一资源标识符)大括号内的链接来标识您的链接的位置。

You can try this:你可以试试这个:

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

A short code version...一个简短的代码版本...

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


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

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*/
    }
String url = "http://www.example.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

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

Intent getWebPage = new Intent(Intent.ACTION_VIEW, Uri.parse(MyLink));          
startActivity(getWebPage);

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.使用这个简单的代码在 android 应用程序中查看您的网站。

Add internet permission in manifest file,在清单文件中添加互联网权限,

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

Chrome custom tabs are now available: Chrome 自定义标签现在可用:

The first step is adding the Custom Tabs Support Library to your build.gradle file:第一步是将自定义选项卡支持库添加到您的 build.gradle 文件中:

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

And then, to open a chrome custom tab:然后,打开一个 chrome 自定义选项卡:

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更多信息: https : //developer.chrome.com/multidevice/android/customtabs

The response of MarkB is right. MarkB 的回答是对的。 In my case I'm using Xamarin, and the code to use with C# and Xamarin is:就我而言,我使用的是 Xamarin,与 C# 和 Xamarin 一起使用的代码是:

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/此信息取自: https : //developer.xamarin.com/recipes/android/fundamentals/intent/open_a_webpage_in_the_browser_application/

Based on the answer by Mark B and the comments bellow:根据 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);
    }
}

android.webkit.URLUtil has the method guessUrl(String) working perfectly fine (even with file:// or data:// ) since Api level 1 (Android 1.0). android.webkit.URLUtil有方法guessUrl(String)工作得很好(即使使用file://data:// ),因为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.查看完整的guessUrl代码以获取更多信息。

Okay,I checked every answer but what app has deeplinking with same URL that user want to use?好的,我检查了每个答案,但是哪个应用程序具有与用户想要使用的相同 URL 的深层链接?

Today I got this case and answer is browserIntent.setPackage("browser_package_name");今天我得到了这个案例,答案是browserIntent.setPackage("browser_package_name");

eg :例如:

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

Thank you!谢谢!

Simply go with short one to open your Url in Browser:只需使用简短的方法即可在浏览器中打开您的网址:

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("YourUrlHere"));
startActivity(browserIntent);
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.该错误是由于 URL 无效而发生的,Android 操作系统无法为您的数据找到操作视图。 So you have validate that the URL is valid or not.所以你已经验证了 URL 是否有效。

Short & sweet Kotlin helper function:简短而甜蜜的Kotlin辅助函数:

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

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

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:不必将 IT 置于特定活动中,因为您可以像这样使用它:

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:或者,如果您想在活动之外启动它,只需在活动实例上调用 startActivity 即可:

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.这是因为如果没有应用程序来处理意图,它会返回 null。

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.如果没有定义协议,则此方法默认为 HTTP,因为有些网站没有 SSL 证书(HTTPS 连接所需的证书),如果您尝试使用 HTTPS 而没有 SSL 证书,这些网站将停止工作. Any website can still force over to HTTPS, so those sides lands you at HTTPS either way任何网站仍然可以强制使用 HTTPS,因此无论哪种方式,这些方面都会让您使用 HTTPS


Because this method uses outside resources to display the page, there is no need for you to declare the INternet permission.由于此方法使用外部资源来显示页面,因此您无需声明 Internet 权限。 The app that displays the webpage has to do that显示网页的应用程序必须这样做

//OnClick Listener //点击监听器

  @Override
      public void onClick(View v) {
        String webUrl = news.getNewsURL();
        if(webUrl!="")
        Utils.intentWebURL(mContext, webUrl);
      }

//Your Util Method //你的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);
        }

    }

Kotlin科特林

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

From Anko library methodAnko库方法

fun Context.browse(url: String, newTask: Boolean = false): Boolean {
    try {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.data = Uri.parse(url)
        if (newTask) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }
        startActivity(intent)
        return true
    } catch (e: ActivityNotFoundException) {
        e.printStackTrace()
        return false
    }
}

A new and better way to open link from URL in Android 11.在 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)
    }

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 https://medium.com/androiddevelopers/package-visibility-in-android-11-cc857f221cd9https://developer.android.com/training/package-visibility/use-cases#avoid-a-disambiguation-dialog

Check whether your url is correct. 检查您的网址是否正确。 For me there was an unwanted space before url. 对我来说,URL前没有多余的空格。

Basic Introduction: 基本介绍:

https:// is using that one into the "code" so that no one in between can read them. https://在“代码”中使用该代码,因此介于两者之间的任何人都无法读取它们。 This keeps your information safe from hackers. 这样可以使您的信息免受黑客攻击。

http:// is using just sharing purpose, it's not secured. http://只是出于共享目的,因此不安全。

About Your Problem: 关于您的问题:
XML designing: XML设计:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.sridhar.sharedpreferencesstackoverflow.MainActivity">
   <LinearLayout
       android:orientation="horizontal"
       android:background="#228b22"
       android:layout_weight="1"
       android:layout_width="match_parent"
       android:layout_height="0dp">
      <Button
          android:id="@+id/normal_search"
          android:text="secure Search"
          android:onClick="secure"
          android:layout_weight="1"
          android:layout_width="0dp"
          android:layout_height="wrap_content" />
      <Button
          android:id="@+id/secure_search"
          android:text="Normal Search"
          android:onClick="normal"
          android:layout_weight="1"
          android:layout_width="0dp"
          android:layout_height="wrap_content" />
   </LinearLayout>

   <LinearLayout
       android:layout_weight="9"
       android:id="@+id/button_container"
       android:layout_width="match_parent"
       android:layout_height="0dp"
       android:orientation="horizontal">

      <WebView
          android:id="@+id/webView1"
          android:layout_width="match_parent"
          android:layout_height="match_parent" />

   </LinearLayout>
</LinearLayout>

Activity Designing: 活动设计:

public class MainActivity extends Activity {
    //securely open the browser
    public String Url_secure="https://www.stackoverflow.com";
    //normal purpouse
    public String Url_normal="https://www.stackoverflow.com";

    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView=(WebView)findViewById(R.id.webView1);

    }
    public void secure(View view){
        webView.setWebViewClient(new SecureSearch());
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.loadUrl(Url_secure);
    }
    public void normal(View view){
        webView.setWebViewClient(new NormalSearch());
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.loadUrl(Url_normal);

    }
    public class SecureSearch extends WebViewClient{
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String Url_secure) {
            view.loadUrl(Url_secure);
            return true;
        }
    }
    public class NormalSearch extends WebViewClient{
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String Url_normal) {
            view.loadUrl(Url_normal);
            return true;
        }
    }
}

Android Manifest.Xml permissions: Android Manifest.Xml权限:

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

You face Problems when implementing this: 实施此方法时,您会遇到问题:

  1. getting The Manifest permissions 获取清单权限
  2. excess space's between url 网址之间有多余的空格
  3. Check your url's correct or not 检查您的网址是否正确

If you want to do this with XML not programmatically you can use on your TextView:如果您想不以编程方式使用 XML 执行此操作,您可以在 TextView 上使用:

android:autoLink="web"
android:linksClickable="true"

Try this..Worked for me! 试试这个。为我工作!

    public void webLaunch(View view) {
            WebView myWebView = (WebView) findViewById(R.id.webview);
            myWebView.setVisibility(View.VISIBLE);
            View view1=findViewById(R.id.recharge);
            view1.setVisibility(View.GONE);
            myWebView.getSettings().setJavaScriptEnabled(true);
            myWebView.loadUrl("<your link>");

        }

xml code :- xml代码:-

 <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webview"
        android:visibility="gone"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        />

--------- OR------------------ - - - - - 要么 - - - - - - - - -

String url = "";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

Try this one OmegaIntentBuilder 试试这个OmegaIntentBuilder

OmegaIntentBuilder.from(context)
                .web("Your url here")
                .createIntentHandler()
                .failToast("You don't have app for open urls")
                .startActivity();
dataWebView.setWebViewClient(new VbLinksWebClient() {
     @Override
     public void onPageFinished(WebView webView, String url) {
           super.onPageFinished(webView, url);
     }
});




public class VbLinksWebClient extends WebViewClient
{
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url)
    {
        view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url.trim())));
        return true;
    }
}

try this code试试这个代码

AndroidManifest.xml AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
   package="com.example.myapplication5">

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

    <application
    android:usesCleartextTraffic="true"
    android:allowBackup="true"
    .....
     />
     <activity android:name=".MainActivity"
        android:screenOrientation="portrait"
        tools:ignore="LockedOrientationActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
 </manifest>

MainActivity.java主活动.java

import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends Activity {
    private WebView mWebview;
    String link = "";// global variable
    Resources res;// global variable

    @Override


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.home);

        loadWebPage();
    }

    public void loadWebPage()
    {
        mWebview = (WebView) findViewById(R.id.webView);
        WebSettings webSettings = mWebview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        final Activity activity = this;
        mWebview.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
            }
        });
        mWebview.loadUrl("http://www.google.com");

    }

    public void reLoad(View v)
    {
        loadWebPage();
    }
}

Layout.xml布局.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="335dp"
        android:layout_height="47dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="9dp"
        android:layout_marginTop="8dp"
        android:paddingLeft="10dp"
        android:paddingTop="5dp"
        android:text="URL : https://ktmmovie.co/"
        android:textSize="18dp"
        android:layout_marginLeft="9dp"
        android:layout_alignParentLeft="true" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/floatingActionButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_marginStart="7dp"
        android:layout_marginLeft="7dp"
        android:layout_marginEnd="8dp"
        android:layout_toEndOf="@+id/textView"
        android:layout_toRightOf="@+id/textView"
        android:clickable="true"
        android:src="@android:drawable/ic_popup_sync"
        android:layout_marginRight="8dp"
        android:layout_alignParentRight="true"
        android:onClick="reLoad"/>

    <WebView
        android:id="@+id/webView"
        android:layout_width="401dp"
        android:layout_height="665dp"
        android:layout_below="@+id/textView"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="3dp"
        android:layout_marginLeft="3dp"
        android:layout_marginTop="3dp"
        android:layout_marginBottom="7dp" />


</RelativeLayout>

Kotlin Developers can use this Kotlin 开发人员可以使用这个

var webpage = Uri.parse(url)
    if (!url.startsWith("http://") && !url.startsWith("https://")) {
        webpage = Uri.parse("http://$url")
    }
    val intent = Intent(Intent.ACTION_VIEW, webpage)
    if (intent.resolveActivity(packageManager) != null) {
        startActivity(intent)
    }

Kotlin Solution Kotlin 解决方案

All the answers were opening the url in default app for that url.所有答案都是在url的默认应用程序中打开 url。 I wanted to always open any url in the browser.我想总是在浏览器中打开任何 url。 I needed some solution in kotlin and implemented the code below.我需要 kotlin 中的一些解决方案并实现下面的代码。

fun getPackageNameForUrl(context: Context, url: String): String? {
    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
    val resolveInfo = context.packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY)
    return resolveInfo?.activityInfo?.packageName
}

fun openInBrowser(context: Context, url: String) {
    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
    val packageName = getPackageNameForUrl(context, "http://")
    packageName?.takeIf { 
        it == "android" 
    }?.let { intent.setPackage(defaultBrowserPackageName); }
    startActivity(context, intent, null)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM