When an activity with "singleTask" launchMode comes to Foreground - Android - android

I have an activity with "singleTask" mode. when this activity goes to background by taping on home key or other application, which methods will be called if it backs to foreground?
onCreate(Bundle savedInstanceState) with savedInstanceState != null
onRestoreInstanceState(Bundle savedInstanceState)
I think because there is one instance of this activity, it doesn't need to save and restore its state and it retain its own state always. am I right?

The sequence of methods that will be invoked is as follows,(in case when Android has killed the process hosting the Activity while the application was in the background, ) when Activity with singleTask mode comes in foreground:
1.onCreate 2.onStart 3.onRestoreInstanceState and 4.onResume
Below is sample code to demonstrate the concept: Activity Declaration in AndroidManifest.xml: <activity android:name="Second" android:launchMode="singleTask"></activity>
public class Second extends Activity {
EditText mEdit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imageview_not);
if (savedInstanceState!=null){
Log.e("onCreate of Actiity", savedInstanceState.getString("editval")); }
mEdit=(EditText) findViewById(R.id.editText1);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.e("Second", "onResume");
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.e("Second", "onStart");
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
outState.putString("editval", mEdit.getText().toString());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
Log.e("Second", "onRestoreInstanceState");
if (savedInstanceState!=null){
Log.e("onRestoreInstanceState", savedInstanceState.getString("editval"));
}
}
}
For illustration purpose, I am just using Edit Text and Android saves its state during configuration change, or when user press HOME etc.
Note that onSaveInstanceState(Bundle outState) is called before an activity may be killed so that when it comes back some time in the future it can restore its state using onRestoreInstanceState(Bundle savedInstanceState).
Also as mentioned by David in another Answer,If Android has not killed the process hosting the Activity, then bringing the task from the background to the foreground will not cause either onCreate() nor onRestoreInstanceState() to be called.

If Android has not killed the process hosting the Activity, then bringing the task from the background to the foreground will not cause either onCreate() nor onRestoreInstanceState() to be called. The Activity doesn't need to be created (it already exists) and the state doesn't need to be restored, because it hasn't been changed.
If, however, Android has killed the process hosting the Activity while the application was in the background, when the user returns to the application Android will create a new process for the application, create a new instance of the Activity, call onCreate() passing the saved instance Bundle as a parameter. It will also call onRestoreInstanceState() passing the saved instance Bundle as a parameter.

Related

Relaunch app when resuming from background

Can I prevent app from resuming when it's killed by other process?
I have problem where I have Singleton class instance in Application class, it holds through app all my info about user and stuff gathered from API. When I open app from background(if it's killed by some process) I getting null on User Model(Picture paths, Name...) and app crushes.
Best way for me is app relaunch from launcher screen and get all info again, not resuming. Any solution for this?
Can I prevent app from resuming when it's killed by other process?
There are three ways an app can be "resumed", by a call to either onCreate, onStart, or onResume. Which one is called depends on how your app was "suspended", and what happens to it while in this state.
onResume follows onPause, which occurs when another app is brought to the foreground.
onStart (onRestart) follows onStop, which occurs when your app is no longer visible.
onCreate follows onPause or onStop if your memory is lost to another app.
When I open app from background(if it's killed by some process) I
getting Nulls on User Model(Picture paths, Name...)
Try persisting this user data in onSaveInstanceState
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(STATE_USER, mUser);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
and restoring it in either onCreate or onRestoreInstanceState
static final String STATE_USER = "user";
private String mUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore user data from saved state
mUser = savedInstanceState.getString(STATE_USER);
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
text.setText(savedInstanceState.getString(STATE_USER));
}

Can we destroy activity without call stop() method?

In activity life cycle to execute as like.
onCreate()
onDestroy()
it means without call stop() method in activity life cycle.
how it is possible ?
Use finish(); to destroy activity.
You don't need to call stop() method. Android system automatically go thru those life cycle methods.
But apparently onDestroy() always called after onStop().
If you want to kill activity just call finish(), it will destroy your activity.
But remember again onStop() always called as system level, follows the activity life cycle if you call finish().
Note: If system kills your application or activity to utilize memory there is no guarantee to call these methods from activity life cycle.
public class ExampleActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.empty);
System.out.println("in onCreate");
finish();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
System.out.println("in onDestroy");
}
}
when the activity run then call onCreate() method and onDestroy()
method

Android Save Instance State

I have created two activities A and B. In the Activity A, using onSaveInstanceState method I am saving bundle value ex(outState.putString("selectSaveDate", this.CalSelectedDate)) and going to the Activity B. When I hit back button to the Activity A , In the oncreate method the bundle value is null. I am unable to get my saved value in the oncreate method.
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.clear();
Log.i("bundleSave", "tester1" + this.CalSelectedDate);
outState.putString("selectSaveDate", this.CalSelectedDate);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null){
Log.i("todolist", "dsa" + savedInstanceState.getString("selectSaveDate"));
}
}
You only store data in a bundle in the OnSaveInstanceState method to persist data when your activity is destroyed and re-created (such as when rotating the screen or when the android os may decide to kill your activity if it is low on resources). When you launch activity B on top of your currently executing activity A, A is put in to a stopped state (therefore, your A activity is not destroyed). Also, when you come back from onStop, the next method that is called is onStart() (technically onRestart() is called be before onStart() but I find that callback is rarely ever implemented.
In conclusion, if your trying to keep persist data between launching an activity on top of your currently executing activity, you can just store that data in instance variables for that activity. If your trying to persist data between app launches then your going to want to look into storing data in Android's built in sqllite database or Android's SharedPreferences.
You should also obtain a real good understanding of the Activity lifecycle (its tricky but needed to code successfully in android):
http://developer.android.com/training/basics/activity-lifecycle/index.html
please try to Override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter like this:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "How are you");
// etc.
}
it will get passed in to onCreate and also onRestoreInstanceState where you'd extract the values like this:
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
or follow activity life cycle for better understanding.

onCreate being called on Activity A in up navigation

So I have an Activity A and an Activity B. I want Activity A to be able to navigate to Activity B with the press of a button. That works, but when I use the up navigation(the home button in the action bar) to navigate back to Activity A, onCreate() is called again and the old information that the user typed in is lost.
I've seen: onCreate always called if navigating back with intent, but they used Fragments, and I'm hoping not to have to redesign the entire app to use fragments. Is there any way I can stop onCreate() from being called every time Activity A becomes active again?
This behavior is totally fine and wanted.
The system might decide to stop Activities which are in background to free some memory.
The same thing happens, when e.g. rotating the device.
Normally you save your instance state (like entered text and stuff) to a bundle and fetch these values from the bundle when the Activity is recreated.
Here is some standard code I use:
private EditText mSomeUserInput;
private int mSomeExampleField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO inflate layout and stuff
mSomeUserInput = (EditText) findViewById(R.id.some_view_id);
if (savedInstanceState == null) {
// TODO instanciate default values
mSomeExampleField = 42;
} else {
// TODO read instance state from savedInstanceState
// and set values to views and private fields
mSomeUserInput.setText(savedInstanceState.getString("mSomeUserInput"));
mSomeExampleField = savedInstanceState.getInt("mSomeExampleField");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// TODO save your instance to outState
outState.putString("mSomeUserInput", mSomeUserInput.getText().toString());
outState.putInt("mSomeExampleField", mSomeExampleField);
}
You can make the up button behave like pressing back, by overriding onSupportNavigateUp()
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
If you want to navigate from child to parent without recreating the parent (calling onCreate method), you may set the android:launchMode="singleTop" attribute for the parent activity in your AndroidManifest.xml

Android onPause and onResume Method

Am trying to implementent onPause() and onResume(), such that when am out of the activity the the text in my text view is still there, but its displaying "null" when i start the the activity please assist!
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
etPassenger.setText(""+ gotPassenger );
etStaffNumber.setText("" + gotStaffNumber);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
etPassenger.setText(""+ gotPassenger );
etStaffNumber.setText("" + gotStaffNumber);
}
I think gotPassenger and gotStaffNumber vars are null - if you want to save them than you have to use prefs or save them to some bundle to restore later.
When you are minimizing your activity your variables becoming null.
Add the following code in your activity,
#Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
savedInstanceState.putString("gotPassenger",gotPassenger);
savedInstanceState.putString("gotStaffNumber",gotStaffNumber);
}
And, in your onCreate() method, add the following,
if(savedInstanceState!=null)
{
etPassenger.setText(savedInstanceState.getString("gotPassenger"));
etStaffNumber.setText(savedInstanceState.getString("gotStaffNumber"));
}
When you are leaving your activity, you will loose the data stored inside gotPassenger and gotStaffNumber.
If you want to reuse them after exiting your application, you have to use SharedPreferences to save them first and retrieve them when you are back.
If you want to save your data even when closing your app you need to use sharedPreferences. Here's how you use them

Categories

Resources