简体   繁体   中英

how onSaveInstanceState keep the latest state of the Activity even if the Activity destroyed or stopped

In this class, i am Overriding both of onSaveInstanceState and onRestoreInstanceState methods, it enabled me to keep the last state of the activity while rotating screen, however, if i navigated to another activity , or i went to Home of my device, it doesn't keep the latest state and start a new state.

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putSerializable("mylist",mAdapter);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    savedInstanceState.getSerializable("mylist");

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {
        ViewConfiguration config = ViewConfiguration.get(this);
        Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
        if (menuKeyField != null) {
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        }
    } catch (Exception ex) {
        // Ignore
    }
    //setHasOptionsMenu(true);
    recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
    if (savedInstanceState != null && savedInstanceState.getSerializable("mylist")!=null) {

        savedInstanceState.getSerializable("mylist");
        update_START();
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(mAdapter);
    }else {
        update_START();
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(mAdapter);
    }
}

can any body tell me what should i add to inforce my Activity to keep its latest state even if the activity has been destroyed, should i add any block of code to any other activities?

my onPostExecute method is as follows:

@Override 
    protected void onPostExecute(ArrayList<MovieEntity> result) {
        mAdapter=null;
        mAdapter = new ImagesAdapter(getBaseContext(), result);
        recyclerView.setAdapter(mAdapter);
    }

This is my Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.prof_mohamed.movieapp">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<receiver
    android:name=".ConnectivityReceiver"
    android:enabled="true">
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity" android:label="Pop Movies">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".DetailActivity" android:label="MovieDetail"></activity>
</application>

It supposed that when i navigate between activities or even between other applications, then return to my first running app, it should restore its latest saved state before starting navigation to other Activities or apps.

If you want to save state for later use, you can write necessary data in either sqlite db or persistence storage. By this kind of design you have to save all data required to make activity in same state. There are other options also but saving data in permanent storage fit for your need and safe. (Assuming you want an activity always persist it state event it destroyed) OnSaveInstanceState and OnRestoreInstanceState automatically save views state (view with id defined in xml) not only for rotation but also for activity kill by system for memory requirement. So you have to save view state also. (for ex edittext with entered data or selected check box etc)

First of all, you are not using the savedInstanceState.getSerializable("mylist") correctly, you should save and cast the object in a variable and use it:

List list = (List) savedInstanceState.getSerializable("mylist");

At this point, The bundle is restored only in the onCreate method (for example on rotation when the activity is destroyed then re-created)

To support saving the instance state on activity navigation or when the home button is pressed (which call onStop then onStart), put the same logic in the if condition inside the onRestoreInstanceState which is called after onStart .

in developer options "do not keep activities" option was enabled, you have to make it disabled, and now every thing is running, saving state in Activities navigation, Home button navigation, and screen rotation besides Overriding both of these methods

@Override

protected void onRestoreInstanceState(Bundle savedInstanceState) {

    super.onRestoreInstanceState(savedInstanceState);
    if (savedInstanceState != null && savedInstanceState.getSerializable("mylist")!=null) {

        savedInstanceState.getSerializable("mylist");
    }
}

@Override protected void onRestoreInstanceState(Bundle savedInstanceState) {

super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getSerializable("mylist");

}

@Override protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    savedInstanceState.getSerializable("mylist");

}

will make your app save its state completely ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM