Android:将搜索查询转发到处理搜索的单个活动

znq*_*znq 4 search android android-activity

我有一个活动处理搜索(ACTIVITY_1),当我在此活动内/从此活动使用搜索(通过手机上的SEARCH按钮)时,它可以正常工作.

但是,当我通过实现并将查询字符串转发到我的Search_Activity.class(ACTIVITY_1)时,使用来自其他活动(ACTIVITY_2..x)onNewIntent的搜索

@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);
    }

}
Run Code Online (Sandbox Code Playgroud)

它总是首先暂停ACTIVITY_2,然后转到ACTIVITY_2的 onCreate().

  • 为什么它在已经存在的情况下重新创建我的ACTIVITY_2并且不直接转到onNewIntent?
  • 还有其他方法可以将搜索查询直接转发到ACTIVITY_1吗?例如,通过Manifest.xml中的设置
  • 是否可以自动将所有搜索查询自动转发到ACTIVITY_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>
Run Code Online (Sandbox Code Playgroud)

Ret*_*ier 11

我不确定我是否了解您所描述的事件链,但是在这种情况下,您需要如何配置应用程序ACTIVITY_1是您在用户按下"搜索"时始终要从所有其他活动启动的搜索活动按钮.

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

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

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

</application>
Run Code Online (Sandbox Code Playgroud)

使用此方法,您应该能够从除ACTIVITY_1之外的所有操作中删除intent-filters,并且您不需要onNewIntent在任何其他活动中使用该处理程序.