intent.getCategories() 虽然已设置,但为空

intent.getCategories() is null although it was set

我正在使用此 intent-filter 配置 Activity 在网站中嵌入的脚本调用时启动我的应用程序:

<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="myapp" />
</intent-filter>

这很好用,因为我的测试设备 HTC One M8 with Android 6.0 按设计启动了应用程序。我可以在 Activity 的 onCreate 方法中使用此代码访问 URL 的查询参数:

Intent intent = getIntent();
  if (intent != null) {
    if (intent.getAction() != null) {
      if (intent.getAction().equals(Intent.ACTION_VIEW)) {
        if (intent.getCategories() != null) {
          if (intent.getCategories().contains(Intent.CATEGORY_BROWSABLE)) {
            Uri uri = intent.getData();
            uri.getQueryParameter("id")
            // launch another activity with this information
          }}}}} // flattened for this question

不幸的是,一台测试设备是装有 Android 6.0 的三星 Galaxy S6。我无法访问查询参数,因为日志状态 intent.getCategories()null。这怎么能用在 HTC 而不是三星设备呢?

我的假设是 Galaxy S6 可能比 HTC 有更多的 RAM,因此可能存储 activity 更长的时间(?)结果是 Intent 仍然是 运行 的初始意图schema intent-filter 之前的应用启动了 Activity。有什么想法可以确保 schema 意图在应用程序收到后立即使用吗?

Category test 的文档指出

For an intent to pass the category test, every category in the Intent must match a category in the filter.

这也意味着,当意图本身没有类别时,意图可能会通过此测试。所以你不应该依赖这些类别的存在,从而返回 null。不同的设备也预装了不同的浏览器。这些可能会产生不同的意图。三星可能不认为您的脚本 link 可浏览。

相反,您应该只依赖操作和数据

Intent intent = getIntent();
if (intent != null && Intent.ACTION_VIEW.equals(intent.getAction())) {
    Uri data = intent.getData();
    if (data != null && "myapp".equals(data.getScheme())) {
        data.getQueryParameter("id")
        // launch another activity with this information
    }
}

或者,如果需要,甚至可以仅基于数据。