2011-01-26 87 views
2

我有一个MapActivity,当按下搜索按钮时将显示Android搜索框。 SearchManager管理对话框,并将用户的查询传递给可搜索的活动,该活动搜索SQLite数据库并使用自定义适配器显示结果。Android onSearchRequested()回调到调用活动

这工作正常 - 我从数据库显示正确的结果。

但是,我想要做的是在用户单击搜索结果时,将结果显示在地图上的MapActivity中。目前,这意味着启动一个新的MapActivity,使用Bundle传递搜索结果。

我曾想过更简洁的方法是将搜索结果传递回原始活动,而不是开始新的活动。目前,我的活动堆栈进入MapAct - > SearchManager - >搜索结果 - >新建MapAct。这意味着从新的MapAct中按“返回”将返回到查询结果,然后返回到原始的MapAct。

似乎在搜索结果中,调用finish()不会导致在调用MapActivity中调用onActivityResult。

任何想法如何得到这个回调并保持一个合理的活动堆栈?

回答

5

我一直在挖掘这个确切问题的答案,并最终找到了一些可行的方法。我不得不做出原始调用活动可搜索的活动,所以我在清单条目是这样的:

<activity android:name=".BaseActivity" 
      android:launchMode="singleTop"> 
    <!-- BaseActivity is also the searchable activity --> 
    <intent-filter> 
     <action android:name="android.intent.action.SEARCH" /> 
    </intent-filter> 
    <meta-data android:name="android.app.searchable" 
       android:resource="@xml/searchable"/> 
    <!-- enable the base activity to send searches to itself --> 
    <meta-data android:name="android.app.default_searchable" 
       android:value=".BaseActivity" /> 
</activity> 

然后,而不是与真正的搜索活动搜索在这个活动中,手动startActivityForResult,这然后将允许您将setResultfinish回复到原来的通话活动。

我在blog post here中了解了更多细节。

1

我终于发现了一个不涉及singleTop的解决方案。

首先,在你的活动,源于搜索,覆盖startActivityForResult:

@Override 
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) { 
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) { 
     int flags = intent.getFlags(); 
     // We have to clear this bit (which search automatically sets) otherwise startActivityForResult will never work 
     flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK; 
     intent.setFlags(flags); 
     // We override the requestCode (which will be -1 initially) 
     // with a constant of ours. 
     requestCode = AppConstants.ACTION_SEARCH_REQUEST_CODE; 
    } 
    super.startActivityForResult(intent, requestCode, options); 
} 

Android将永远(出于某种原因)与Intent.FLAG_ACTIVITY_NEW_TASK标志启动ACTION_SEARCH意图,出于某种原因,但如果该标志是设置,onActivityResult将永远不会(正确)在您的原始任务中调用。

接下来,在您的可搜索Activity中,您只需在用户选择某个项目时调用setResult(Intent.RESULT_OK, resultBundle)即可。

最后,你实现你的原始活动onActivityResult(int requestCode, int resultCode, Intent data)resultCodeIntent.RESULT_OKrequestCode是你请求的代码不变(AppConstants.ACTION_SEARCH_REQUEST_CODE在这种情况下)作出适当的反应。