今天用uc浏览器上淘宝,当我点击购买的时候,系统会自动跳转并打开本地的淘宝app的对应页面,于是在网上研究了一下,是这么回事:本地的app和html网页是有一定的约束和规范的,也就是说,我在html网页上的超链接的某一些内容和本地app中的需要打开的activity所设置的action是一样的。我们来看一一个栗子:
新建一个launcher.html
<html>
<body>
<a href="testapp://haha/open?name=lisi&age=30&from=ucbroswer">启动apk</a>
</body>
</html>
可以看到launcher.html的内容很简单,就是一个简单的超链接,这里我们主要用于启动app的连接是:"testapp://haha/open"
注意这里的"testapp://haha/open"就是刚才说的,必须遵守nativeapp中的action中声明的一些规范,另外"name=lisi&age=30&from=ucbroswer"是我们从html向native app中传递的值。
我们启动MainActivity.java这个类,因此需要该工程的androidManifest.xml中增加对该类声明的action,这个action中就是规范html中的跳转连接的写法,如下:
<activity
android:name="com.example.htmllauncher.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<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="haha"
android:pathPrefix="/open"
android:scheme="testapp" />
</intent-filter>
</activity>
我们可以看到增加了这样一个action标签:
<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="haha"
android:pathPrefix="/open"
android:scheme="testapp" />
</intent-filter>
其中<data>标签,就是对html的规范,再来看看我们html中的跳转连接,是这样写的:testapp://haha/open ,这样就可以通过该超链接跳转到该MainActivity当中了。
好了,现在通过MainActivity如何获得html当中传递过来的数据呢??看下面的代码:
Intent i_getvalue = getIntent();
String action = i_getvalue.getAction();
if(Intent.ACTION_VIEW.equals(action)){
Uri uri = i_getvalue.getData();
if(uri != null){
String name = uri.getQueryParameter("name");
String age= uri.getQueryParameter("age");
String from = uri.getQueryParameter("from");
Toast.makeText(MainActivity.this,"name is :"+name+"==age is :"+age+"==from is :"+from,Toast.LENGTH_SHORT).show();
}
}
好了,这样就完成了html打开本地app并且传递参数的简单功能,希望大家喜欢。。