我有一个处理搜索的活动(活动_1),当我在此活动中/从该活动中使用搜索(通过手机上的“搜索”按钮)时,效果非常好。

但是,当我使用另一个活动的搜索时(ACTIVITY_2..x)通过实施 onNewIntent 并将查询字符串转发到我的 Search_Activity.class (活动_1)

@Override
protected void onNewIntent(Intent intent) {
    Log.i(TAG, "onNewIntent()");

    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        Log.i(TAG, "===== Intent: ACTION_SEARCH =====");
        Intent myIntent = new Intent(getBaseContext(), Search_Activity.class);
        myIntent.setAction(Intent.ACTION_SEARCH);
        myIntent.putExtra(SearchManager.QUERY, intent.getStringExtra(SearchManager.QUERY));
        startActivity(myIntent);
    }

}

它总是暂停 活动_2 首先然后转到 onCreate() 的 活动_2.

  • 为什么它重新创建了我的 活动_2 当它已经存在并且不直接转到 onNewIntent 时?
  • 有没有其他方法可以将搜索查询直接转发到 活动_1?例如通过 Manifest.xml 中的设置
  • 是否可以将所有搜索查询自动转发到 活动_1 甚至没有实施 onNewIntent 在所有其他活动中?

目前我必须放一个 <intent-filter> 在每个活动中“激活”我的自定义搜索,然后将查询转发到通过 onNewIntent (如上图所示)。

<activity android:name=".Another_Activity"
    android:theme="@style/MyTheme">
    <intent-filter>
        <action android:name="android.intent.action.SEARCH" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
    <meta-data android:name="android.app.searchable"
        android:resource="@xml/searchable" />
</activity>
有帮助吗?

解决方案

我不确定我是否理解您描述的事件链,但以下是您需要如何配置应用程序的情况,如果 ACTIVITY_1 是当用户按下“搜索”时您始终希望从所有其他活动启动的搜索活动按钮。

假设搜索按钮在 Activity1 上完美运行,您只需向应用程序添加一些粘合元数据,告诉它所有其他 Activity 都应使用 ACTIVITY_1 进行搜索,如下面的清单片段所示:

<application>
  <meta-data 
     android:name="android.app.default_searchable"
     android:value=".ACTIVITY_1" />

   <!-- All your activities, service, etc. -->

</application>

使用此功能,您应该能够从除 ACTIVITY_1 之外的所有活动中删除意图过滤器,并且您不需要使用 onNewIntent 您的任何其他活动中的处理程序。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top