Android onSearchRequested() callback to the calling activity

点点圈 提交于 2019-12-04 15:02:35

I've been digging around for an answer to this exact question and finally found something that works. I had to make the original calling activity also the searchable activity, so my entry in the manifest looks like this:

<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>

And then instead of searching in this activity, manually startActivityForResult with the real search activity, which will then allow you to setResult and finish back to the original calling activity.

I went into a bit more detail in a blog post here.

I finally discovered a solution to this that does not involve singleTop.

First, in your Activity that originates the search, override 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 will always (for some reason) start the ACTION_SEARCH intent with the Intent.FLAG_ACTIVITY_NEW_TASK flag, for some reason, but if that flag is set, onActivityResult will never be (correctly) called in your originating task.

Next, in your searchable Activity, you just call setResult(Intent.RESULT_OK, resultBundle) as normal when the user selects an item.

Finally, you implement onActivityResult(int requestCode, int resultCode, Intent data) in your originating Activity and respond appropriately when the resultCode is Intent.RESULT_OK and the requestCode is your request code constant (AppConstants.ACTION_SEARCH_REQUEST_CODE in this case).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!