finish() vs startActivity()

548 views Asked by At

According to Android documentation, finish() does exactly what the "back" button does. So basically onStop() is called when I call finish().

I tried to override onStateSaveInstance() to save the current state, but it is never called. However, if I go to the previous activity by creating a new Intent and using startActivity(), the method onStateSaveInstance() is called. Is there a reason for that?

1

There are 1 answers

4
CommonsWare On

So basically onStop() is called when I call finish().

Not necessarily. onStop() is called when your activity is no longer visible. finish() only triggers a call to onStop() if the activity is visible when you call finish().

I tried to override onStateSaveInstance() to save the current state, but it is never called

Correct. You are destroying the activity. There is no instance state to be saved.

However, if I go to the previous activity by creating a new Intent and using startActivity(), the method onStateSaveInstance() is called

Not necessarily. It will depend on Intent flags, android:launchMode in the manifest, etc.

Is there a reason for that?

onSaveInstanceState() will not be called when your activity is being destroyed. There is no instance state to be saved, as the instance is going away.