
I was reading a good post written by Luis G. Valle about SearchViews and he explains two lifecycle ways:
- Default: searchable activity receives a call to
onCreate
with anACTION_SEARCH
intent. This will create two instances of your searchable activity (one on top of the other). - If you set
android:launchMode
tosingleTop
: searchable activity receives a call toonNewIntent
with anACTION_SEARCH
intent.
Commonly, a new activity is opened during a search and it could be good to keep a history of searches, each search done is a activity opened. If you don’t want that your app works in this way, you can set your activity launch mode as singleTop (I’ve explained a little about it here), and your app won’t need to open a new activity, but you can get the ACTION_SEARCH intent on the same activity, specifically on the onNewIntent() method.
Just to complement, I have another way that I’ve used in my apps to try. I really don’t think it is a better way than the second way explained by Luis but, keeping the first way, I intercept the intent on the method onStartActivity. Something like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Override | |
public void startActivity(Intent intent) { | |
if (Intent.ACTION_SEARCH.equals(intent.getAction())) { | |
//Do something with the query… | |
} else { | |
super.startActivity(intent); | |
} | |
} |
In this way I avoid that a new activity is opened if the intent is related to search.