Android中使用Scheme协议打开App

本文详细解析了Android中Intent与Intent-Filter的工作原理及应用。通过实例展示了如何使用Intent-Filter注册特定的Intent,使App能响应来自网页或其他App的调用,并解释了如何在App内部解析和获取传递的参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于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>

通过网页打开:

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
</head>
<body>
    <a href="testapp://testmodule:8000/showtitle?query1=1&title=hello">打开APP</a>
</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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值