Android控制元件之WebView(網頁調轉回APP)
阿新 • • 發佈:2019-01-26
問題來源:網頁跳轉回應用
APP開啟網頁,網頁放置在伺服器中(例如,APP開啟百度網頁),開啟網頁之後在某一時刻需要從網頁在跳轉回到APP。
實現原理:使用URI再加上Intent來實現。
URI介紹:
就Android平臺而言,URI主要分三個部分:scheme, authority and path。其中authority又分為host和port。格式如下:
scheme://host:port/path
舉個實際的例子:
程式碼實現:
網頁程式碼
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="m://my.com/">跳轉回app</a><br/>
</body>
</html>
AndrodMainfest.xml程式碼
在AndroidManifest的清單檔案對應的Activity標籤的intent-filte中加入如下元素:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="my.com"
android:scheme="m" />
</intent-filter>
示例截圖如下:
Activity程式碼
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri=Uri.parse(url);
if(uri.getScheme().equals("m")&&uri.getHost().equals("my.com")){
String arg0=uri.getQueryParameter("arg0");
String arg1=uri.getQueryParameter("arg1");
}else{
view.loadUrl(url);
}
return true;
}
});
當在Activity程式碼中新增loadURL(網頁程式碼)後,執行APP,當點選網頁中的調轉回APP連線之後,程式碼就會回到上述Activity程式碼中的shouldOverrideUrlLoading()函式中,此時就可以寫我們自己想要實現的功能了。
擴充套件:
Uri分為兩種:
1. 不帶引數uri m://my.com/
2. 帶引數uri m://my.com/?arg0=0&arg1=1
應用場景 QQ和微信等SDK來實現分享網頁