美文网首页我爱编程
WebView通过隐式启动跳转到Activity页面

WebView通过隐式启动跳转到Activity页面

作者: kevenZheng | 来源:发表于2018-04-16 11:40 被阅读0次

利用系统提供的隐式启动,从Html网页中跳转到Activity。V

<!DOCTYPE HTML>
<html>
<body>

<a href="myapp://tonative/param?id=123" style=" color:#666; fontsize:50px;">OpenCihon</a>

</body>
</html>

当我们在webview里加载上面的代码,并点击OpenCihon后,系统会去寻找能处理uri为”myapp://tonative/param?id=123”的Activity,默认情况下当然是没有的,所以我们可以把要打开的Activity按照约定的uri协议进行声明

 <activity android:name=".FanhuaResultActivity">
            <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="tonative"
                    android:scheme="myapp" />
            </intent-filter>
        </activity>

我们可以通过声明不同的host实现打开不同的Activity,在打开的Activity里可以通过如下代码获取html页面传过来的参数

Intent intent = getIntent();
        String action = intent.getAction();
        if(Intent.ACTION_VIEW.equals(action)){
            Uri uri = intent.getData();
            if(uri != null){
                String id = uri.getQueryParameter("id");
                Toast.makeText(this,id,Toast.LENGTH_LONG).show();
            }
        }

但这样其实有个问题,我们一般会在自己的WebviewActivity里给

wv.setWebViewClient(new WebViewClient(){})

从而实现在本页内的跳转都是由本Webview打开,而不是跳转到系统浏览器处理。这样设置后,‘href=”myapp://tonative/param?id=123”’这样的请求也被拦截到了本Webview里,从而失效,因此,我们需要做一个判断

 wv.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                String scheme = Uri.parse(url).getScheme();//还需要判断host
                if (TextUtils.equals("myapp", scheme)) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                return false;
            }
        });

return true,表明这次请求交给系统来处理。
这样就可以实现使用隐式启动,打开需要的Activity。

相关文章

网友评论

    本文标题:WebView通过隐式启动跳转到Activity页面

    本文链接:https://www.haomeiwen.com/subject/ovwskftx.html