I hope someone can point out where I am being thick.
I am calling a webviewclient and overriding loading to catch mailto links (working) and a specific external URL (not working). the specific link is just a launch in browser for non mobile site link. I'd love to figure this out.
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("mailto:")) {
url = url.replaceFirst("mailto:", "");
url = url.trim();
try {
url = URLDecoder.decode(url,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
int subjectStart = url.indexOf("subject=");
int subjectStop = url.indexOf("&body=");
String subject = url.substring(subjectStart,subjectStop);
subject = subject.replace("subject=", "");
String bod = url.substring(subjectStop);
bod = bod.replace("&body=", "");
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("test/plain");
i.putExtra(Intent.EXTRA_SUBJECT,subject);
i.putExtra(Intent.EXTRA_TEXT, bod);
startActivity(i);
return true;
} else if ( url.contains("[EXTERNAL LINK I WANT TO OPEN IN BROWSER]") == true ) {
//tried without intent and nothing
Uri uri = Uri.parse(url.toString());
Intent browserIntent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(browserIntent);
return false; //tried true here too
} else {
view.loadUrl(url);
return true;
}
}
[...]
I tried playing with return true and return false there and I tried a version with no intent for the browser. Almost all of them would open the link in the webview instead of the browser, and the ones that didn't, didn't do anything.
The mailtos are working great, what am I missing on the external links?
If you need it, here's how I call the webclient.
public class MyWebViewClient extends WebViewClient {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
switcher = (ViewSwitcher) findViewById(R.id.profileSwitcher);
WebView webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("[MY SITE]");
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.setWebViewClient(new MyWebViewClient()
{
public void onPageFinished(WebView view, String url)开发者_开发问答 {
if (REFRESH_WEB ==1){
startScan();
REFRESH_WEB++;
}
}
});
You had it write the first time you should return true when you want to launch in the browser, also you are doing some extra work on the mailto scheme. You can just use the built in MailTo class. Also +1 on @CommonsWare comment something to look into for sure if this isn't working for you.
public boolean shouldOverrideUrlLoading(Webview view, String url){
if(url.startsWith("mailto:"){
MailTo mt = MailTo.parse(url);
//populate intent with mt.getSubject(), mt.getBody(), etc
//start activity
return true;
}
else if(url.contains("youtube.com")){
Uri uri = Uri.parse(url.toString());
Intent browserIntent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(browserIntent);
return true;
}
else return false;
}
精彩评论