在Android中,可以通过在AndroidManifest.xml文件中定义intent-filter来定义scheme。具体用法如下:

  1. 定义scheme

在AndroidManifest.xml文件中添加以下代码段:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <application
        ...>

        <activity android:name=".MainActivity">
            <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="example.com"
                    android:scheme="myapp" />
            </intent-filter>
        </activity>

    </application>

</manifest>

这里定义了一个名为'myapp'的scheme,在浏览器中输入'myapp://example.com'可以启动MainActivity。

  1. 定义host

在定义scheme时,可以通过添加host来指定要打开的页面。例如:

<data
    android:host="example.com"
    android:scheme="myapp" />

这里定义了host为'example.com',在浏览器中输入'myapp://example.com'可以启动MainActivity。

  1. 定义path

在定义scheme时,可以通过添加path来指定要打开的页面的路径。例如:

<data
    android:host="example.com"
    android:path="/product"
    android:scheme="myapp" />

这里定义了path为'/product',在浏览器中输入'myapp://example.com/product'可以启动MainActivity中的'商品详情'页面。

  1. 定义参数

在定义scheme时,可以通过添加参数来传递数据。例如:

<data
    android:host="example.com"
    android:path="/product"
    android:scheme="myapp" />

<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="example.com"
        android:scheme="myapp" />

    <data android:scheme="https" />

</intent-filter>

这里定义了一个参数,通过在浏览器中输入'myapp://example.com/product?id=123'可以传递参数'id=123'。在MainActivity中可以通过以下代码获取参数:

Uri uri = getIntent().getData();
String id = uri.getQueryParameter("id");
Android App Scheme 定义指南:从基础到参数传递

原文地址: https://www.cveoy.top/t/topic/ofmA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录