Android 使用Scheme实现从网页启动APP
http://www.jianshu.com/p/1cd02fe1810f
通过使用Scheme,可以实现用手机的浏览器(内置或第三方)访问一个网页,启动自己的应用,或者在一个应用使用WebView.loadUrl()方法启动另外一个应用。
首先我们来看一下网页跳转到应用的实现原理 在Android平台而言,URI主要分三个部分:scheme, authority,path, queryString。其中authority又分为host和port。格式如下: scheme://host:port/path?qureyParameter=queryString 举个例子: http://www.orangecpp.com:80/tucao?id=hello
在Android的Manifest配置文件中,<intent-filter>配置项中有<data>配置 其中<data>包含内容有:
<data android:host="" android:mimeType="" android:path="" android:pathPattern="" android:pathPrefix="" android:port="" android:scheme="" android:ssp="" android:sspPattern="" android:sspPrefix=""/>通过配置<data>可以对网页进行过滤,符合匹配条件的网页才跳转到应用。一般只需要设置host和scheme即可。
下面来讲一下具体的实现步骤 1.首先我们写一个测试网页test.html
<!DOCTYPE html> <html> <body> <h1>Test Scheme</h1> <!--自动加载隐藏页面跳转--> <iframe src="myscheme://www.orangecpp.com:80/mypath?key=mykey" style="display:none"></iframe> <!--手动点击跳转--> <a href="myscheme://www.orangecpp.com:80/mypath?key=mykey">Click</a> </body> </html>2.创建一个Android测试工程,修改Manifest文件,给想要接收跳转的Activity添加<intent-filter>配置
<activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <!--需要添加下面的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:scheme="myscheme"/> </intent-filter> </activity>3.在配置好<intent-filter>的Activity里即可获取外部跳转的参数信息。
public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent =getIntent(); Log.e(TAG, "scheme:" +intent.getScheme()); Uri uri =intent.getData(); Log.e(TAG, "scheme: "+uri.getScheme()); Log.e(TAG, "host: "+uri.getHost()); Log.e(TAG, "port: "+uri.getPort()); Log.e(TAG, "path: "+uri.getPath()); Log.e(TAG, "queryString: "+uri.getQuery()); Log.e(TAG, "queryParameter: "+uri.getQueryParameter("key")); } }4.在浏览器中或者通过另外一个应用的WebView.loadUrl()方法访问test.html,可以看到我们的应用会自动启动,在控制台可以看到log信息。
E/MainActivity: scheme:myscheme E/MainActivity: scheme: myscheme E/MainActivity: host: www.orangecpp.com E/MainActivity: port: 80 E/MainActivity: path: /mypath E/MainActivity: queryString: key=mykey E/MainActivity: queryParameter: mykey大功告成!现在你可以根据此方法做更加复杂的操作了,比如在Activity里获取到path参数,根据path的不同跳转到不同的Activity,同时可以传query的参数进行相应的操作处理。