【问题标题】:Android: forward search queries to one single activity that handles searchAndroid:将搜索查询转发到处理搜索的单个活动
【发布时间】:2009-12-15 11:59:37
【问题描述】:

我有一个活动处理搜索 (ACTIVITY_1),当我在此活动中/从该活动中使用搜索(通过手机上的“搜索”按钮)时,它可以完美运行。

但是,当我通过实现 onNewIntent 使用来自另一个活动 (ACTIVITY_2..x) 的搜索并将查询字符串转发到我的 Search_Activity.class (ACTIVITY_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);
    }

}

它总是先暂停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>

【问题讨论】:

    标签: android search android-activity


    【解决方案1】:

    我不确定我是否理解您所描述的事件链,但如果 ACTIVITY_1 是您始终希望在用户按下“搜索”按钮。

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

    <application>
      <meta-data 
         android:name="android.app.default_searchable"
         android:value=".ACTIVITY_1" />
    
       <!-- All your activities, service, etc. -->
    
    </application>
    

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

    【讨论】:

    • 非常感谢 Reto。你知道吗?这是我在 SearchManager 文档中读到的内容之一,并且从我尝试实现搜索的第一天起就有了。但是,它总是显示 Google Web Search,而不是我自己的搜索。我终于明白了原因:我的 android:value=".ACTIVITY_1" 中出现了一个愚蠢的错字,所以 Android 从未找到正确的 Activity,因此直接进入网络搜索。感谢您强迫我再次查看这种平静的代码。
    • 根据文档,元数据标签进入源活动,而不是应用程序。
    猜你喜欢
    • 2011-07-02
    • 2011-06-15
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    相关资源
    最近更新 更多