【Android】H5调用native并通过url传递参数

2017-12-05  本文已影响140人  renkuo

H5调用native并且接收url传递参数(通过Intent读取Url上面的参数)
url示例:scheme://shop/item/item_id/569c64d85efb115f5e8b4568(H5端)
参考地址:https://stackoverflow.com/questions/11773958/open-android-application-from-a-web-page
业务场景是一个navite页面,既可以native间正常调用,也可以通过h5调用
1、Activity在AndroidManifest.xml配置参数:

<activity
    android:name=".activity.ProductDetailHotActivity"
    android:screenOrientation="portrait"
    android:theme="@style/Theme.CustomTitle">
    <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="shop.item"
            android:scheme="scheme" />
    </intent-filter>
</activity>

2、获取参数:
如果一个页面都是通过h5跳转的这个步骤可以省略

private void getIntentData() {
    Intent intent = getIntent();
    if(intent != null) {//如果是native,拿到id走正常跳转,不需要通过url跳转
        id = intent.getStringExtra(KEY_ID);
        Log.i(TAG, "id:" + id);

        if(TextUtils.isEmpty(id)) {//通过url跳转并获取参数
            getIntentDataByUri(intent);
        }
    }
}   

3、getIntentDataByUri()方法实现

private void getIntentDataByUri(Intent intent) {
    if(intent == null) {
        return;
    }

    Uri uri = intent.getData();
    if(uri != null) {
        List<String> params = uri.getPathSegments();
        if(params==null || params.size()<2) {
            return;
        }

        String first = params.get(0); // "item_id"
        String second = params.get(1); // "569c64d85efb115f5e8b4568"
        Log.i(TAG, "first:" + first + ", second:" + second);

        this.id = second;
    }
}

错误不足之处或相关建议欢迎大家评论指出,谢谢!如果觉得内容可以的话麻烦喜欢(♥)一下

上一篇 下一篇

猜你喜欢

热点阅读