It is necessary that when clicking on any link that does not lead to the pages of the site http://site.com , the choice of browsers to open the site is launched.

The whole application is this mobile version of the site packed in a webview, in order not to violate the integrity of all links that go not to the domain of the site need to be opened in the browser, and not in the application.

Program Code:

import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; public class MainActivity extends AppCompatActivity { private WebView web; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); web = (WebView) findViewById(R.id.web); web.setWebViewClient(new WebViewClient()); web.loadUrl("https://site.com"); web.getSettings().setJavaScriptEnabled(true); } @Override public void onBackPressed() { if (web.canGoBack()) { web.goBack(); } else { super.onBackPressed(); } } } 

    2 answers 2

    You need to describe WebViewClient in a similar way:

     private class MyWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (Uri.parse(url).getHost().equals("www.example.com")) { // This is my web site, so do not override; let my WebView load the page return false; } // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } } 

    And, accordingly, install it in WebView :

     WebView myWebView = (WebView) findViewById(R.id.webview); myWebView.setWebViewClient(new MyWebViewClient()); 

      In short, as follows:

       // В этой переменной у нас хранится адрес сайта String site = "http://site.com/"; Uri siteUri = Uri.parse(site); // Создаём интент Intent openLinkIntent = new Intent(Intent.ACTION_VIEW, siteUri); // Открываем в браузере startActivity(openLinkIntent); 

      It is worth noting that if for the links of this type there are several applications in the system, a menu will appear to select the appropriate one (if the default application is not installed).

      And the startActivity method is in Context (if you suddenly call it outside the activation class).

      • I need the browser to open all sites except this, and this site is only in the current webview - Slaxor
      • @Slaxor where will you keep these links? Will you have a long text that may contain links? Or what? If not, you can process first which link was clicked on, and, if necessary, open it in the browser. - Peter Samokhin
      • The whole application is this mobile version of the site packed in a webview, in order not to violate the integrity of all links that go not to the domain of the site need to be opened in the browser, and not in the application. - Slaxor