Confusion between onPause() onStop() onResume() - java

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.

Related

Why do codes work in the onCreate() instead of onResume()

I'm like an intermediate in android programming. I decided to take a deep dive into the Activity lifecycle methods and I realised something, like why do methods Toasts.show() and many other methods get called again when the activity is resumed. If the methods are in the onCreate so why then if you like go to another activity and return it will still give you a Toast message. Let me give an example.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
{Your Initialization go here }
//Toas message
Toast.makeText(code).show();
}
}
So imagine you leaving this activity for another one and then coming back... why does it still show the Toast message. Because since the lifecycle is
OnCreate
onResume
onStart
onPause
onstop
onDestroy
And when you come back to your MainActivity it calls the
onResume
onStart.
So if onCreate is not called...So how does the Toast message show.
Please someone should help me answer this I've searched all day but couldn't find answers.
accoording to lifecycle of activity https://developer.android.com/guide/components/activities/activity-lifecycle, if there is no memory engouh the app process will kill, so when you back to your activity on created will call another time.
the image below for clarification:
When your activity goes in the background, and memory is required for other apps. It is possible that the system frees up space even though your activity is in the background with ONPAUSED state. and now if you navigate to your activity, since the saved instance is removed due to memory requirements. instead of ONRESUME, ONSTART is called. you can read more about it here: https://developer.android.com/guide/components/activities/activity-lifecycle
and see this image for better understanding: https://developer.android.com/guide/components/images/activity_lifecycle.png
This uncertainty is one of the reasons why we now mostly use view models for a sizeable app.

How to run code when app is re-entered after going to home (Android)

I want to run some code after I hit my home button and the re-open the app. How do I run code when the app is re-opened (Not After Being Killed) in android-studio?
you can use onStop() method or onDestroy() , if you will close totally that Activity use onDestroy() and if you just will put it in background you can use onStop()
Doc for onDestroy()
Perform any final cleanup before an activity is destroyed. This can
happen either because the activity is finishing (someone called
finish() on it, or because the system is temporarily destroying this
instance of the activity to save space. You can distinguish between
these two scenarios with the isFinishing() method.
Doc for onStop()
Called when you are no longer visible to the user. You will next
receive either onRestart(), onDestroy(), or nothing, depending on
later user activity.
i saw you edited your question, look at the lifecycle
Like sagar says, you can use onResume() in order to recover your current Activity
You can perform the action in onResume() method. This is the state in which the app interacts with the user. The app stays in this state until something happens to take focus away from the app. Do note that there is no differentiation between Activity coming from background to foreground or Activity created from scratch. onResume() will be called whenever app enters foreground state.
In order to differentiate it in onResume() you need to maintain a boolean flag. You can set the flag in onStop() and check it in onResume().
This approach will only work, if the OS hasn't killed the process, hosting your Activity, due to memory constraints. In this case your Activity will be recreated.
You can use onRestart() since when you left your activity to go home it goes into onStop() and after that when you launch it system will call onRestart() the onStart().
for more info refer following ans:
https://stackoverflow.com/a/35476531/7271231

Activity Create and resume again and again in Nougat Version

I am navigating from Activity A to Activity B without finishing Activity A (because i want to go back on it and have some variables values).
In Activity B I launch camera and save captured image but the problem is, after capture camera the Activity A is re-create and resumed, causing re initialization of my variables.
How to stop it?
Note: The problem occurs only in Nougat Version.
The thing you want to know here is about the complete activity life cycle. Basically to summerize them they are
OnCreate, - called when activity is created
OnStart, - called when activity starts
OnREsume, - when activity gets back
OnPause, - when activity is overlapped
OnStop, - when activity is closes
and onDestroy - when finish() is called.
Though you have not mentioned how you started an activity and got back to the same activity, the correct way to get back to previous activity is by calling
finish()
on camera activity.
I guess you have got back to activity A by using
Intent i= new Intent(this, ActvityA.class)
startActivity(i)
which is the the correct way to do.
Just call the finish() when you want to get back to Activity A from B (Here B is in top of A).
Additional
If you want to pass data from activity B to A, just put something called as Intent Extra or Bundle
Activity A is create again and resume, so my variables are initialize again. How to stop it.
Yes that is normal. First rule with Android programming is that your activity can be killed at any time. So to not loose your variables you have to save them at the right moment.
You would do that to override onSaveInstanceState() putting your variables in the bundle.
Then you can retrieve them in onCreate() from the function parameter.

My activity get closed without entering OnSaveInstanceState handle

I'm closing my 2nd activity by clicking on a button, then triggering a "finish()" method. This shall do the same as pressing the back button on my device, and it does.
The problem is that it doesn't enter OnSaveInstanceState, which shall happen when destroying an activity. The result is that after re-entring this activity again, savedInstanceState == null, thus I cannot save my last variables' state.
Button closeButton = (Button) findViewById(R.id.bClose);
closeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
From official documentation of the onSaveInstaceState :
Do not confuse this method with activity lifecycle callbacks such as
onPause(), which is always called when an activity is being placed in
the background or on its way to destruction, or onStop() which is
called before destruction. One example of when onPause() and onStop()
is called and not this method is when a user navigates back from
activity B to activity A: there is no need to call
onSaveInstanceState(Bundle) on B because that particular instance will
never be restored, so the system avoids calling it. An example when
onPause() is called and not onSaveInstanceState(Bundle) is when
activity B is launched in front of activity A: the system may avoid
calling onSaveInstanceState(Bundle) on activity A if it isn't killed
during the lifetime of B since the state of the user interface of A
will stay intact.
You have two examples of when the onSaveInstanceState is not called. The most important part is the beginning :
Do not confuse this method with activity lifecycle callbacks such as onPause(), which is always called when an activity is being placed in the background or on its way to destruction.
You should not expects that onSaveInstanceState will be called each time. This method is here to allow the Activity to save its UI elements. If you are trying to persists a variable value or something else (i.e. a value contained inside a View but which should be for the life time of the application - a username for example), you should use another mechanism like SharedPreferences.
Sources
Activity.onSaveInstanceState(Bundle) reference

Should startActivity always run the started Activities onCreate?

I have a main activity and a sub activity.
The main activity starts the sub activity using startActivity, and passes an object in the intent.
The sub activity reads the object out of the intent in its onCreate action.
The sub activity updates the object, then returns to the main activity using startActivity, again passing the updated object back.
However, the main activities onCreate function is not called, so the code it contains to read the passed object does not run.
Further investigation indicated that the main activity onPause event is firing, i.e. it is only paused when the sub activity runs, so when the sub activity starts the main activity again, it just onResumes.
Does anyone know if there would be any disadvantages if I moved my data restore/store activities to the onResume and onPause events?
I'm not using the onCreate savedInstanceState, should I be?
How else do you pass a set of data items between Activities without using a database or those preferences? Should I be using a database? I have about 20 fairly individual data items.
Any help would be much appreciated,
Frink
I would check out the startActivityForResult() method rather than just startActivity()
That should give you a means to pass things back to the calling activity.
From http://developer.android.com/reference/android/app/Activity.html:
Sometimes you want to get a result back from an activity when it ends. For example, you may start an activity that lets the user pick a person in a list of contacts; when it ends, it returns the person that was selected. To do this, you call the startActivityForResult(Intent, int) version with a second integer parameter identifying the call. The result will come back through your onActivityResult(int, int, Intent) method.
Have a look at the Activity life cycle here.
Also, consider starting your sub-activity using StartActivityForResult.
It is more likely calling onResume() or onStart() depending on the child activity and how much control it takes.
Look at this page about 3/4's down at the graph.
http://developer.android.com/guide/topics/fundamentals.html
The parent never gets destroyed so it wouldn't have to recreate it. It should just get paused. You can override onResume() and onStart() just as you would onCreate().
Edit: Is there anything given to the user in the subactivity? It sounds like you don't actually need an activity you just need a java class that you can call methods on.
Why don't you call startActivityForResult from the main activity and get the data back in onActivityResult ? This is the normal way to do it.

Categories

Resources