Android中使用Scheme协议打开App

对于activity,我们可以注册intent-filter声明自己对什么样的intent感兴趣,网页或其它App就能通过intent来打开我们的App并传递参数了,intent-filter里的action,category,data必须都匹配。

        <activity android:name=".TestActivity">
            <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="testapp"
                    android:host="testmodule"
                    android:path="/showtitle"
                    android:port="8000" />
            intent-filter>
        activity>

通过网页打开:


<html>
<head>
    <title>testtitle>
head>
<body>
    <a href="testapp://testmodule:8000/showtitle?query1=1&title=hello">打开APPa>
body>
<html>

通过其它App打开:

Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse("testapp://testmodule:8000/showtitle?query1=1&title=hello"));
startActivity(intent);

在App中获取传递的参数:

public class TestActivity extends AppCompatActivity {
    private static String TAG="TestActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

        Uri uri=getIntent().getData();
        if (uri!=null){
            String scheme=uri.getScheme();
            String host=uri.getHost();
            int port=uri.getPort();
            String path=uri.getPath();
            String query=uri.getQuery();
            String title=uri.getQueryParameter("title");
            Log.d(TAG,"scheme:"+scheme+",host:"+host+",port:"+port+",path:"+path+",query:"+query+",title:"+title);
        }
    }
}
2019-09-06 12:01:17.220 6272-6272/com.xy.testapp D/TestActivity: scheme:testapp,host:testmodule,port:8000,path:/showtitle,query:query1=1&title=hello,title:hello

你可能感兴趣的:(Android)