将URI与<data>匹配,例如AndroidManifest中的http://example.com/something

Mah*_*oni 9 regex android deep-linking android-manifest android-xml

我正在努力使用文件中的<data>元素AndroidManifest.xml来使我的URI匹配工作.我想匹配以下URI:

不是

我得到它主要是与合作

<data android:scheme="http"
      android:host="example.com"
      android:pathPattern="/..*" />

<data android:pathPattern="/..*/" />
Run Code Online (Sandbox Code Playgroud)

但它仍然匹配http://example.com/something/else.

我该如何排除这些?

Sim*_*mas 8

不幸的是,可用于pathPattern标记的通配符非常有限,并且通过纯xml目前无法实现所需的通配符.

这是因为一旦你接受了"/.*"所有被接受的东西(包括斜杠).由于我们无法提供不被接受的数据标签,唯一的方法是检查活动内部的数据.以下是如何完成您的工作:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Uri data = getIntent().getData();

    Log.d("URI", "Received data: " + data);
    String path = data.getPath();

    // Match only path "/*" with an optional "/" in the end.
    // * to skip forward, backward slashes and spaces
    Pattern pattern = Pattern.compile("^/[^\\\\/\\s]+/?$");
    Matcher matcher = pattern.matcher(path);
    if (!matcher.find()) {
        Log.e("URI", "Incorrect data received!");
        finish();
        return;
    }

    // After the check we can show the content and do normal stuff
    setContentView(R.layout.activity_main);

    // Do something when received path data is OK
}
Run Code Online (Sandbox Code Playgroud)

清单中的活动如下所示:

<activity
    android:name=".MainActivity"
    android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:scheme="http"
              android:host="example.com"
            android:pathPattern="/.*"/>
    </intent-filter>
</activity>
Run Code Online (Sandbox Code Playgroud)

如果您不希望自己的活动检查数据是否正确,则必须更改您的要求.

  • 此解决方案的问题在于,一旦您的活动收到了Intent,如果它没有对它执行任何操作,其他活动将无法获得它. (5认同)