Search code examples
androidandroid-searchmanager

Android search onCancel() listener not being called


In the onCreate() method of my main Activity, I setup a callback to the Activity's onCancel() method to be called (I believe) when the search dialog is canceled by the user without issuing a search. Here's my registration code:

SearchManager searchManager = (SearchManager) getApplicationContext().getSystemService(Context.SEARCH_SERVICE);
searchManager.setOnCancelListener(this);

My Activity implements SearchManger.OnCancelListener and my onCancel() method currently is a Log.d() statement. However, whenever I cancel the search dialog (e. g. using the back button), this method is never called.

To be clear, the search functionality works just fine when executed. I just want notification when the user has canceled the search dialog so I can take action. Also, I am using the default Android search dialog that appears at the top of the screen when requested.

Is there some sort of configuration I need, e. g. in the AndroidManifest.xml, in order to support this callback? Or am I just missing/doing something stupid (entirely possible)?


Solution

  • You need to use the Activity context

    SearchManager searchManager = (SearchManager) this.getSystemService(Context.SEARCH_SERVICE);
    

    Also, I believe onDismissListener is recommended over onCancel, as onCancel is only explicit and doesn't get triggered by the back button