Reputation: 39
I know this has been asked multiple times but I went through all the answers and I just cant get it to work. Im trying to make a simple webview app that handles external links in native browser.
package com.example.app;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private WebView webview;
private long backPressedTime;
@Override
public void onBackPressed() {
if (webview.canGoBack()) {
webview.goBack();
} else {
if (backPressedTime + 2000 > System.currentTimeMillis()) {
super.onBackPressed();
return;
} else {
Toast.makeText(getBaseContext(), "Press back again to exit", Toast.LENGTH_SHORT).show();
}
backPressedTime = System.currentTimeMillis();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.webView);
webview.setWebViewClient(new WebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
webview.loadUrl("https://www.myurl.com");
}
}
Any help would be greatly appreciated. Thank you
Upvotes: 0
Views: 875
Reputation: 3739
You can override URL loading with following code. If you want to handle URL loading yourself return true
. If the URL should be opend in the WebView, return false
.
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Insert logic here
}
}
If you just want to open external links you can use following code. In case the opened URL starts with your domain's base URL, false
is returned and the URL is opened in the WebView. Otherwise the ACTION_VIEW
intent is used to open the URL in the browser and true is returned.
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Abort if no URL
if (url == null || !(url.startsWith("http://") ||
url.startsWith("https://"))) {
return false;
}
// Abort if internal URL
if (url.startsWith("http://www.myurl.com") ||
url.startsWith("https://www.myurl.com")) {
return false;
}
// Open external URL in browser
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
});
Notice: You have to handle "http://..." and "https://...". Because the method might get called for both.
Upvotes: 1