首页 文章

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

提问于
浏览
1141

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

29 回答

  • 16

    在2.3,我有更好的运气

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

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

  • 1

    检查您的网址是否正确 . 对我来说,在url之前有一个不需要的空间 .

  • 11
    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;
        }
    }
    
  • 4

    这种方法使用一种方法,允许您输入任何String而不是固定输入 . 如果重复使用多次,这会保存一些代码行,因为您只需要三行来调用该方法 .

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

  • 41

    就像其他人编写的解决方案(工作正常)一样,我想回答相同的问题,但我认为大多数人更愿意使用 .

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

    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.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
    startActivity(intent);
    
  • 67

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

    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 :)
    
    }
    
  • 6

    你也可以这样走

    在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中别忘了添加互联网权限......

  • 3

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

    你可以试试这个:

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

    由于 Api level 1 (Android 1.0), android.webkit.URLUtil 方法guessUrl(String)完全正常(即使 file://data:// ) . 用于:

    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了解更多信息 .

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

    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

  • 6

    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/

  • 2

    Basic Introduction:

    https:// 正在将 https:// 用于"code",以便中间没有人可以读取它们 . 这可以保护您的信息免受黑客攻击 .

    http:// 仅使用共享目的,它不安全 .

    About Your Problem:
    XML designing:

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

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

    实现这个时你遇到问题:

    • 获得 Manifest 权限

    • url之间的多余空间

    • 检查 url's 是否正确

  • 1

    试试吧......为我工作!

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

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

    如果要使用XML而不是以编程方式执行此操作,可以在TextView上使用:

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

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

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

    快乐的编码!

  • 0

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

    另外不要忘记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;
        }
    }
    
  • 7

    Simple, website view via intent,

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

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

    Add internet permission in manifest file,

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

    // OnClick Listener

    @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);
            }
    
        }
    
  • 0

    短代码版本......

    if (!strUrl.startsWith("http://") && !strUrl.startsWith("https://")){
         strUrl= "http://" + strUrl;
     }
    
    
     startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(strUrl)));
    
  • 2149

    根据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);
        }
    }
    
  • 0

    我认为这是最好的

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

    试试这个OmegaIntentBuilder

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

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

    谢谢!

  • 28

    试试这个:

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

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

    试试这个:

    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 .

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

    简单回答

    你可以看到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);
        }
    }
    

    它是如何工作的

    请看一下Intent的构造函数:

    public Intent (String action, Uri uri)
    

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

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

    我需要if check语句吗?

    是 . docs说:

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

    奖金

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

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

相关问题