简体   繁体   中英

onResume() is not called in physical device instead onCreate() is called

Iam little bit amazed with this.I have an onResume() in my activity.Its called and works well in my emulator, but in a physical device samsung galaxy note for specific with jellybean installed,its not called.Instead onCreate() is called all the time.Why this happens?

public void onResume(){
    super.onResume();
    if(firsttime){
        try {
            Toast.makeText(getApplicationContext(), "Resuming Activity",Toast.LENGTH_LONG).show();
            addReminder();
        } catch(Exception exception) {
            exception.printStackTrace();
        }
    } else {
        firsttime=true;
    }
}

This is my code.firsttime is a static boolean variable.It is used to prevent onResume() being called when app is started for the first time

Try to print something inside the onResume and check it in LogCat.... the code inside onResume may be causing this. or else can you elaborate your question?

Considering your current scenario, you should save variable in preferences instead of relying on activities lifecycle since lifecycle depends on many things. Using static variable for this scenario is bad choice in general.I think this should solve your problem.

I think here is what happens, when your app not the Top app, the activity manager actually destroy the activity, it only called

    public void onSaveInstanceState(Bundle savedInstanceState)

no

    onStop

called, so no

    noResume

will be called.

The correct to do this is, when put all states of this activity when

    public void onSaveInstanceState(Bundle savedInstanceState)

called.

and in your onCreate() function, do such thing

  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); // Always call the superclass first

    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
        mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    } else {
        // Probably initialize members with default values for a new instance
    }
    ...
}

to check if you have some saved state.

Most code was copy from android developer site: http://developer.android.com/training/basics/activity-lifecycle/recreating.html

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