Scheme跳轉協議

Scheme協議

Android中的Scheme是一種頁面內跳轉協議,通過自定義Scheme協議,可以跳轉到app中的任何頁面。

  • 服務器可以定製化跳轉app頁面
  • app可以通過Scheme跳轉到另一個app頁面
  • 可以通過h5頁面跳轉app原生頁面

協議格式

 Uri.parse("qh://test:8080/goods?goodsId=8897&name=fuck")
  • qh代表Scheme協議名稱
  • test代表Scheme作用的地址域
  • 8080代表改路徑的端口號
  • /goods代表的是指定頁面(路徑)
  • goodsId和name代表傳遞的兩個參數

Scheme使用

  • 定義一個Scheme
 <activity android:name=".SchemeActivity">
            <!-- 給頁面添加指定的過濾器-->
            <intent-filter>
                 <!--該頁面的路徑配置-->
                <data
                    android:host="test"
                    android:path="/goods"
                    android:port="8080"
                    android:scheme="qh"/>
                <!--下面這幾行也必須得設置-->
                <category android:name="android.intent.category.DEFAULT"/>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.BROWSABLE"/>
            </intent-filter>
        </activity>
  • 獲取Scheme跳轉的參數
Uri uri = getIntent().getData();
        if (uri != null) {
            // 完整的url信息
            String s = uri.toString();
            sb.append(s + "\n");
            // scheme部分
            String scheme = uri.getScheme();
            sb.append("scheme=" + scheme + "\n");
            // host部分
            String host = uri.getHost();
            sb.append("host=" + host + "\n");
            // 訪問路勁
            String path = uri.getPath();
            sb.append("path=" + path + "\n");
            //port部分
            int port = uri.getPort();
            sb.append("port=" + port + "\n");
            // Query部分
            String query = uri.getQuery();
            sb.append("query=" + query + "\n");
            //獲取指定參數值
            String goodsId = uri.getQueryParameter("goodsId");
            sb.append("goodsId=" + goodsId + "\n");
            //列舉所以參數名
            Set<String> queryParameterNames = uri.getQueryParameterNames();
            tv_scheme.setText(sb.toString());
        }
  • 調用方式
 1. 原生調用
 Intent intent1 = new Intent(Intent.ACTION_VIEW, Uri.parse("qh://test:8080/goods?goodsId=8897&name=fuck"));
                startActivity(intent1);
2. html調用
<a href="qh://test:8080/goods?goodsId=8897&name=fuck">打開商品詳情</a>

判斷某個Scheme是否有效

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("qh://test:8080/goods?goodsId=8897&name=fuck"));
List<ResolveInfo> activities = getPackageManager().queryIntentActivities(intent, 0);
boolean isValid = !activities.isEmpty();
if (isValid) {
    startActivity(intent);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章