android Activity Scheme跳转协议

转载:原文https://blog.csdn.net/lishuiyuntian/article/details/77477756

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);
}

猜你喜欢

转载自blog.csdn.net/luvalluo/article/details/80260236