Android从Web页面启动App

前言

今天来讲一下如何从一个外部的网页启动自己的App

实现

首先我们需要模拟一个网页环境,从这个网页里启动我们的App,
先写一个test.html文件


<html>
<body>
<h1>Test Schemeh1>



<a href="myscheme://www.orangecpp.com:80/mypath?key=mykey">Launcha>
body>
html>

然后把这个文件放到项目的assets目录下,如图所示
Android从Web页面启动App_第1张图片

然后在Activity中,我们通过WebView去加载这个页面,代码如下

public class MainActivity extends Activity{
    private WebView webView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        webView = (WebView) findViewById(R.id.webview);
        String fileUrl = "file:///android_asset/test.html";
        webView.loadUrl(fileUrl);
    }
}

运行效果
Android从Web页面启动App_第2张图片

接下来,我们需要在自己的App中进行一些配置,才能够让外部网页启动
找到需要启动的Activity,在清单文件中添加如下代码

  <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:scheme="myscheme"/>
            intent-filter>

如图所示
Android从Web页面启动App_第3张图片

注意这里的data属性,我们指定了scheme:就是通过这个来匹配的
data里面还可以配置其他属性,这样我们就可以从网页启动我们的App了,接下来我们在App中获取一下网页传过来的url

   Intent intent = getIntent();
        String scheme = intent.getScheme();
        if (!TextUtils.isEmpty(scheme)) {
            Uri uri = intent.getData();
            Log.d(TAG, "scheme: " + uri.getScheme());//myscheme
            Log.d(TAG, "host: " + uri.getHost());//www.orangecpp.com
            Log.d(TAG, "path: " + uri.getPath());///mypath
            Log.d(TAG, "port: " + uri.getPort());//80
            Log.d(TAG, "query: " + uri.getQuery());//key=mykey
            Log.d(TAG, "key: " + uri.getQueryParameter("key"));//mykey
        }

结果如下图

Android从Web页面启动App_第4张图片

效果动图

Android从Web页面启动App_第5张图片

你可能感兴趣的:(Android从Web页面启动App)