天天看點

通過Html網頁調用本地安卓app程式代碼

前段時間寫一些移動端的項目,正好項目中遇到與native互動的需求,特此将其整理下來:

一. 通過html頁面打開Android本地的app
  1. 首先在編寫一個簡單的html頁面
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
    </head>
    <body>
        <a href="m://my.com/">打開app</a><br/>
    </body>
</html>
           
  1. 在Android本地app的配置

    在AndroidManifest的清單檔案裡的intent-filte中加入如下元素:

<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="my.com"
                    android:scheme="m" />
</intent-filter>
           

然後使用“手機浏覽器”或者“webview”的方式打開這個本地的html網頁,點選“打開APP”即可成功開啟本地的指定的app

二、如何通過這個方法擷取網頁帶過來的資料

隻能打開就沒什麼意思了,最重要的是,我們要傳遞資料,那麼怎麼去傳遞資料呢?

我們可以使用上述的方法,把一些資料傳給本地app,那麼首先我們更改一下網頁,代碼修改後:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
    </head>
    <body>
        <a href="m://my.com/?arg0=0&arg1=1">打開app</a><br/>
    </body>
</html>
           

(1).假如你是通過浏覽器打開這個網頁的,那麼擷取資料的方式為:

uri = getIntent().getData();  String test1= uri.getQueryParameter("arg0");  String test2= uri.getQueryParameter("arg1");
           

(2)如果使用webview通路該網頁,擷取資料的操作為:

webView.setWebViewClient(new WebViewClient(){
  @Override
  public boolean shouldOverrideUrlLoading(WebView view, String url) {
      Uri uri=Uri.parse(url);
          if(uri.getScheme().equals("m")&&uri.getHost().equals("my.com")){
              String arg0=uri.getQueryParameter("arg0");
              String arg1=uri.getQueryParameter("arg1");

          }else{
              view.loadUrl(url);
          }
      return true;
  }
});