【问题标题】:How can I open a URL in Android's web browser from my application?如何从我的应用程序在 Android 的网络浏览器中打开 URL?
【发布时间】:2011-01-13 04:49:45
【问题描述】:

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

【问题讨论】:

  • 为什么这在某些设备上不起作用?即使有网络浏览器,它也会进入 ActivityNotFoundException。
  • 我看到与@Manu 相同的问题。 Nexus 6 上的基本安装,具有 chrome,但链接导致异常。
  • 我可以隐藏地址栏吗? @Arutha

标签: android url android-intent android-browser


【解决方案1】:

我检查了每个答案,但哪个应用具有与用户想要使用的相同 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);

【讨论】:

  • 好答案。它解释了如何(直接)在特定浏览器上打开 Intent URL,而不依赖于系统选择浏览器。
  • 太好了,这将在 chrome 浏览器而不是您的应用中打开已验证的链接,但是如果未安装 chrome,您也需要处理这种情况。
  • @shanraisshan 确实
【解决方案2】:

实现此目的的常用方法是使用以下代码:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 它没有添加任何有趣的东西。如果没有应用程序处理 URL,甚至将无法工作。会因异常而崩溃。
    • 所有设备都应该有一个应用程序来处理 URL。您可以根据需要添加自己的失败/异常处理,
    • 同意你的看法。
    【解决方案4】:

    在 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

    【讨论】:

      【解决方案5】:

      又短又甜的 Kotlin 辅助函数:

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

      【讨论】:

        【解决方案6】:

        来自Anko库方法

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

        【讨论】:

        • Anko 已弃用。请参阅this page 了解更多信息。
        • @phillipsK Anko 已弃用,但 Android SDK 未弃用
        【解决方案7】:

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

        【讨论】:

          【解决方案8】:

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

          我终于成功了:

          // 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.whatever,因为我已将其用于静态 util 方法,如果您在活动中执行此操作,则不需要。

          【讨论】:

            【解决方案9】:

            试试这个代码

            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

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

            布局.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>
            

            【讨论】:

              【解决方案10】:

              科特林

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

              【讨论】:

                【解决方案11】:
                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 是否有效。

                【讨论】:

                  【解决方案12】:

                  只需简单地在浏览器中打开您的网址:

                  Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("YourUrlHere"));
                  startActivity(browserIntent);
                  

                  【讨论】:

                  • 只能在APP里打开,比如webview之类的。
                  【解决方案13】:

                  简单和最佳实践

                  方法一:

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

                  方法二:

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

                  【讨论】:

                  • Fragment 中使用context!!.packageManager 而不是getPackageManager()
                  【解决方案14】:

                  就像其他人写的解决方案一样(效果很好),我想回答同样的问题,但我认为大多数人更愿意使用的提示。

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

                  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 Custom Tabs 中的 URL。 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)
                  }
                  

                  【讨论】:

                  • 如果网络浏览器出现问题,是否会创建一个新任务来保护源应用程序免受错误和崩溃?
                  • @TheOriginalAndroid 我不明白它与崩溃和网络浏览器有什么关系。请解释您要做什么。
                  • 感谢您的回复。你的帖子很有趣。打开一个新任务有什么好处,尤其是对于网络发布?
                  • @TheOriginalAndroid 只是为了让用户能够切换回您的应用程序,然后再切换回网络浏览器。如果您打开最近的任务屏幕,您将在此处看到 2 个任务而不是一个。此外,您不会在单个任务(属于您的应用程序的任务)中看到 Web 浏览器缩略图,而是看到 2:您的一个应用程序和另一个 Web 浏览器。我认为这种方式不那么令人困惑。
                  • FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET 已弃用
                  【解决方案15】:
                  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;
                      }
                  }
                  

                  【讨论】:

                    【解决方案16】:

                    基本介绍:

                    https:// 在“代码”中使用该代码,这样中间的任何人都无法阅读它们。这可以保护您的信息免受黑客攻击。

                    http:// 仅用于共享目的,不安全。

                    关于您的问题:
                    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>
                    

                    活动设计:

                    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 权限:

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

                    你在实现这个时会遇到问题:

                    1. 获得Manifest权限
                    2. 网址之间有多余的空间
                    3. 检查您的网址是否正确

                    【讨论】:

                      【解决方案17】:

                      通过意图的简单网站视图,

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

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

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

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

                      【讨论】:

                        【解决方案18】:

                        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

                        【讨论】:

                          【解决方案19】:

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

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

                          【讨论】:

                          • 请注意,插件等在 WebView 中被禁用,并且需要 INTERNET 权限。 (reference)
                          • 还要注意.setJavaScriptEnabled(true); 是危险的。
                          【解决方案20】:

                          试试这个:

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

                          【讨论】:

                          • 请注意,插件等在 WebView 中被禁用,并且需要 INTERNET 权限。 (reference)
                          【解决方案21】:

                          试试这个:

                          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。

                          【讨论】:

                          • 除了您的代码和 mbaird 的不一样,据我所知发布的内容。确保您的 URL 具有 http:// 方案 - 显示的异常表明您的 URL 缺少该方案。
                          • 是的!它错过了 http:// ! URL是用户输入的,有没有办法自动格式化?
                          • URLUtil 是检查用户输入的“url”字符串的好方法
                          • if (!url.startsWith("http://") &amp;&amp; !url.startsWith("https://")) 是一个常见错误,它可能会导致您访问像file:// 这样的网址并破坏一些好的用例。尝试使用 URI 类解析 uri 并检查是否存在模式。如果没有,添加“http://”;)
                          • 您需要使用resolveCheck 进行空检查。请参阅offical docs注意:如果设备上没有可以接收隐式 Intent 的应用程序,则您的应用程序在调用 startActivity() 时将崩溃。要首先验证是否存在接收 Intent 的应用,请在 Intent 对象上调用 resolveActivity()。
                          【解决方案22】:

                          试试这个OmegaIntentBuilder

                          OmegaIntentBuilder.from(context)
                                          .web("Your url here")
                                          .createIntentHandler()
                                          .failToast("You don't have app for open urls")
                                          .startActivity();
                          

                          【讨论】:

                            【解决方案23】:

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

                            【讨论】:

                            • “isURL”在哪里定义?
                            【解决方案24】:

                            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/

                            【讨论】:

                              【解决方案25】:

                              android.webkit.URLUtil 的方法 guessUrl(String) 工作得非常好(即使使用 file://data://),因为 Api level 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 code 了解更多信息。

                              【讨论】:

                                【解决方案26】:

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

                                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 权限。显示网页的应用程序必须这样做

                                【讨论】:

                                  【解决方案27】:

                                  试试这个..为我工作!

                                      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代码:-

                                   <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"
                                          />
                                  

                                  --------- 或------------------

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

                                  【讨论】:

                                  • 对于大多数应用来说,添加 WebView 是一种很难的方式。在浏览器中打开 URL 更容易。
                                  【解决方案28】:

                                  如果您想以非编程方式使用 XML 执行此操作,您可以在 TextView 上使用:

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

                                  【讨论】:

                                    【解决方案29】:

                                    根据 Mark B 的回答和下面的 cmets:

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

                                    【讨论】:

                                    • 我会随时雇用你.. 关爱代码。谢谢
                                    【解决方案30】:

                                    我认为这是最好的

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

                                    【讨论】:

                                      猜你喜欢
                                      • 2018-08-18
                                      • 2017-11-06
                                      • 2015-07-11
                                      • 1970-01-01
                                      • 1970-01-01
                                      • 2018-10-21
                                      • 1970-01-01
                                      • 1970-01-01
                                      • 2017-10-03
                                      相关资源
                                      最近更新 更多