SearchView and the Activity Lifecycle

from beautifuldecay.com

I was reading a good post written by Luis G. Valle about SearchViews and he explains two lifecycle ways:

  1. Default: searchable activity receives a call to onCreate with an ACTION_SEARCH intent. This will create two instances of your searchable activity (one on top of the other).
  2. If you set android:launchMode to singleTop: searchable activity receives a call to onNewIntent with an ACTION_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:


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

Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair /  Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair /  Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair /  Alterar )

Conectando a %s