简体   繁体   中英

Confusion between onPause() onStop() onResume()

I am developing an Android app in which I want to check if the user has minimized the application or just come from another activity.

In detail, if the user have started another app, went to the home screen or locked the screen, I want to show the activity where the user will enter the password to access the app. But where or how to check this exactly?

https://developer.android.com/guide/components/activities/activity-lifecycle.html

I was trying onResume() but according to documentation onResume() can be fired if the user's navigating to another activity and coming back.

I'm not very clear on what you are trying to achieve. The life cycle diagram is quite clear if you are wondering which lifecycle method it would hit when something happens. Basically, it's the same to minimise the app and go to another activity. But if you are referring to coming from another activity in your own app, you can distinguish your own activity by adding extra information to the intent you use.

Basically, it's like this:

Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra(key,value);
startActivity(intent);

And in your SecondActivity, you can always retrieve that data like this:

Bundle bundle = getIntent().getExtras();
if ( bundle != null && bundle.containsKey(key) ) {
    value = bundle.getInt(key); // not nessecarily getInt(), you should use according to your value type
    // use the value to tell if it is from your own app
} else {
    // it is not from your own app
}

You can use this mechanism combined with the lifecycle methods. For example, if you use the latter code in your onCreate() method, then whenever the Activity is created, if will check who creates it, which sounds like your what you might want.

As soon as your activity becomes visible it will call OnStart() and as soon as it is ready for the interaction(such as touch ,click etc event). it calls onResume, at this stage your app is running and it is completely in foreground. When your activity start another activity or a dialog box then it calls onPause it means activity is visible but user can not interact with the Activity UI. in case we start another Activity which completely hides the previous activity then its onStop method is called

onPause : Called when another activity comes into the foreground.

onStop : Called when that other activity is completely visible.

onResume : Called when your activity is navigated back to from the onPause state.

Maybe your app was already in the onStop state, so then it would call onRestart .

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