In this blog,
I have talked about activity recreating in android. And will give the some facts related to save the Activity State.
There are a few scenarios in which your activity is destroyed due to normal app behavior, such as
When the user presses the Back button or your activity signals its own destruction by calling finish().
The system may also destroy your activity if it’s currently stopped and hasn’t been used in a long time.
The foreground activity requires more resources so the system must shut down background processes to recover memory.
However, if the system destroys the activity due to system constraints, then although the actual Activity instance is gone,
The system remembers that it existed such that if the user navigates back to it, the system creates a new instance of the activity using a set of saved data that describes the state of the activity when it was destroyed. The saved data that the system uses to restore the previous state is called the “instance state” and is a collection of key-value pairs stored in a Bundle object.
Note: Your activity will be destroyed and recreated each time the user rotates the screen.
How to re-opening the activity
For recreating the activity, you can use the simple recreate() or startActivity(intent).
or can use to reopen the activty by startActivity.
1
2
3
Intent intent=getIntent();
finish();
startActivity(intent);
It was only added in API level 11. If you want to include more devices you can check the API level.
You can use both by making an if statement,
1
2
3
4
5
6
7
8
if(android.os.Build.VERSION.SDK_INT>=11){
recreate();
}
else{
Intent intent=getIntent();
finish();
startActivity(intent);
}
How to Save the Activity State
As your activity begins to stop, the system calls onSaveInstanceState() so your activity can save state information with a collection of key-value pairs.
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
How to Restore Your Activity State
When your activity is recreated after it was previously destroyed, you can recover your saved state from the Bundle that the system passes your activity. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information.
1
2
3
4
5
6
7
8
9
10
11
12
@Override
protectedvoidonCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);// Always call the superclass first
// Check whether we're recreating a previously destroyed instance
Be the first to comment.