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

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.

Related

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

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.

How to know when an Activity dies in a Fragment

I have a fragment that is being loaded by an Activity.
I know things such as
onPause()
onStop()
On stop gets called too late and sometimes not at all.
But my Activity dies I want to know so that I can tell my fragment to clean up.
What is the fastest way?
I'm not realyl sure what your question is, but perhaps you will find this useful.
https://developer.android.com/guide/components/fragments.html#Creating
I suggest reading up on the fragment life-cycle
onDestroy() will be called just before the Fragment is destroyed. This could happen because the parent Activity is also destroyed or because the Fragment is no longer displayed.

Advice on onPause and onResume

If i use the code below will this restore text that has been input into EditTextfields and selected spinner items?
#Override
protected void onPause(){
super.onPause();
}
#Override
protected void onResume(){
super.onResume();
}
or do I have to tell it to save the current values and then restore then when activity is resumed? when I am using the emulator if I don't have these methods in and I go to say home then run my app again it always loads back to the previous state, so my questions is does this actually do antyhing?
Nope, this actually only called the super class onPause() and onResume() without doing anything else. The value in your editbox stay there because even if the app is paused, is still there on the activity stack waiting.
However Android can kill your paused activity and your data will be lost. So you have to save them onPause and restore them on the onResume to avoid this.
No, this code does not do anything. You're overriding these methods, but giving them an implementation of just calling the parent implementation. This is the same as not overriding them in the first place.
It's not absolutely necessary to save/restore state for when you pause/resume. The only reason why you would need to manually do some state saving is if you want to restore state even after your application is killed.
You values still the same in your spinner because the app hasn't been kill yet. It's only put a pause state still in memory. If the app were destroyed the values of your spinner will be back to the onCreate method and whatever value they had at the start.
Look here for what each method does --> https://developer.android.com/reference/android/app/Activity.html
You only need to save state when onDestroy() is called. That only happens when you use the back button or the OS kills the Activity when it is in a stopped state.
If you Activity becomes partially obscured it will be paused but if it is completely obscured it will be stopped.
When it is top of the stack again it will resume or start.
To experiment use Log to write messages to the LogCat when each of events occurs and then you will be able to see when and why they are called.

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