什么是 URL Scheme?
android中的scheme是一種頁面內(nèi)跳轉(zhuǎn)協(xié)議,是一種非常好的實現(xiàn)機制,通過定義自己的scheme協(xié)議,可以非常方便跳轉(zhuǎn)app中的各個頁面;通過scheme協(xié)議,服務器可以定制化告訴App跳轉(zhuǎn)那個頁面,可以通過通知欄消息定制化跳轉(zhuǎn)頁面,可以通過H5頁面跳轉(zhuǎn)頁面等。
URL Scheme應用場景:
客戶端應用可以向操作系統(tǒng)注冊一個 URL scheme,該 scheme 用于從瀏覽器或其他應用中啟動本應用。通過指定的 URL 字段,可以讓應用在被調(diào)起后直接打開某些特定頁面,比如商品詳情頁、活動詳情頁等等。也可以執(zhí)行某些指定動作,如完成支付等。也可以在應用內(nèi)通過 html 頁來直接調(diào)用顯示 app 內(nèi)的某個頁面。綜上URL Scheme使用場景大致分以下幾種:
服務器下發(fā)跳轉(zhuǎn)路徑,客戶端根據(jù)服務器下發(fā)跳轉(zhuǎn)路徑跳轉(zhuǎn)相應的頁面
H5頁面點擊錨點,根據(jù)錨點具體跳轉(zhuǎn)路徑APP端跳轉(zhuǎn)具體的頁面
APP端收到服務器端下發(fā)的PUSH通知欄消息,根據(jù)消息的點擊跳轉(zhuǎn)路徑跳轉(zhuǎn)相關(guān)頁面
APP根據(jù)URL跳轉(zhuǎn)到另外一個APP指定頁面
URL Scheme如何使用:
1、設置Scheme
<activity
android:name=".GoodsDetailActivity"
android:theme="@style/AppTheme">
<!--要想在別的App上能成功調(diào)起App,必須添加intent過濾器-->
<intent-filter>
<!--協(xié)議部分,自定義設置
如:xl://goods:8888/goodsDetail?goodsId=10011002
-->
<data android:scheme="xl"
android:host="goods"
android:path="/goodsDetail"
android:port="8888" />
<!--下面這幾行也必須得設置-->
<category android:name="android.intent.category.DEFAULT"/>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.BROWSABLE"/>
</intent-filter>
</activity>
2、獲取Scheme跳轉(zhuǎn)的參數(shù)
Uri uri = getIntent().getData();
if (uri != null) {
// 完整的url信息
String url = uri.toString();
Log.e(TAG, "url: " + uri);
// scheme部分
String scheme = uri.getScheme();
Log.e(TAG, "scheme: " + scheme);
// host部分
String host = uri.getHost();
Log.e(TAG, "host: " + host);
//port部分
int port = uri.getPort();
Log.e(TAG, "host: " + port);
// 訪問路徑
String path = uri.getPath();
Log.e(TAG, "path: " + path);
List<String> pathSegments = uri.getPathSegments();
// Query部分
String query = uri.getQuery();
Log.e(TAG, "query: " + query);
//獲取指定參數(shù)值
String goodsId = uri.getQueryParameter("goodsId");
Log.e(TAG, "goodsId: " + goodsId);
}
3、調(diào)用方式
h5網(wǎng)頁調(diào)用
<a href="xl://goods:8888/goodsDetail?goodsId=10011002">打開商品詳情</a>
原生調(diào)用
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("xl://goods:8888/goodsDetail?goodsId=10011002"));
startActivity(intent);
js調(diào)用 (沒有安裝app或者href無效就會跳轉(zhuǎn)下載頁面)
function android(){
window.location.href = "xl://goods:8888/goodsDetail?goodsId=10011002";
window.setTimeout(function(){
window.location.href = "http://【這里是下載頁面】.html";
},2000);
};
3、如何判斷一個Scheme是否有效
PackageManager packageManager = getPackageManager();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("xl://goods:8888/goodsDetail?goodsId=10011002"));
List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
boolean isValid = !activities.isEmpty();
if (isValid) {
startActivity(intent);
}