简体   繁体   中英

Android: How to save objects initialised in the Application class when the System Restarts my App Process

In my application class i have a Object which is used by all the activities that are launched from Launcher screen. The problem is, In low memory case the system automatically Restarts my Application (i could see that in Settings -> Application -> Running Process Tab). Since it is restarting (that happens once the app is in background), the Object which i am using throughout is being reset to null.

My Scenario:

In my Launcher Activity, i am hitting the DB and takes the value in a thread and using Setter & Getter i am setting the Object value in the Application class.

After setting it i am moving to four activities from there A(Launcher) -> B -> C -> D

Now i am going background and my device is running in Low memory, my process is killed and restarted at this point (ie, in background).

At the restart my Object is reset to null, Now if i launch my app from the recentlist or through the Launcher, it is still launching the last Activity from where i went background in the above case it is Activity D, where i am accessing the Object which throws Null-pointer.

My question is,

  1. Is there any way to save the Object at the Application class level when system kills it (like we do in the Activity onSaveInstanceState).

You can do something like use Shared Preferences to save data about the object in order to rebuild it. (You can also use the db, local files,etc).

But if I can deviate a bit from the specific question: do you know why your app is being killed off for memory reasons? Are you targeting a really low end device or hardware? Or maybe your app needs to be optimized a bit save/reuse memory?

You save last state of object onSaveInstanceState and get back onRestoreInstanceState You can find all informations about recreating Activity in this best practice . I suggest you to read Activity Life Cycle

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    // Always call the superclass so it can restore the view hierarchy
    super.onRestoreInstanceState(savedInstanceState);

    // Restore state members from saved instance
    mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
    mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}

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