I call an activity called Activity1 from an Activity called MainActivity using the following:
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
So, when the control comes to Activity1. The normal activity lifecycle is started. i.e onCreate() is called and so on.
when i click the back button when the control is in Activity1. The finish method is called, which in turn calls the onDestroy() and now the control is back with the MainActivity screen.
#Override
public void onBackPressed() {
Log.d(TAG, "onBackPressed()");
finish();
}
The next time i call Activity1. The onCreate is called again as i called the onDestroy (when i pressed the back button) from the previous call.
Question:
1. is there a way to pass control back to the MainActivity when the back button is pressed without having to call the "finish()" method?
2. problem with calling finish, every time i call Activity1 from MainActivity, A new instance of Activity1 is created. that is the lifecycle again starts from onCreate()..
i do not want this to happen as this is has become a major performance issue.
The main point i'm looking for is whether i can start the activity1 from the resume state rather than oncreate, when i call it after the first time.
I don't believe you need to call the "finish()" method on onBackPressed. Android does that for you when you press the back button. The onBackPressed is used to last minuet tidy up (save stuff to sharepreferences, etc).
Android default behaviour is to call onCreate whenever a new activity is place on the screen. You cannot call a new Intent without this to happen.
I'm not sure why this is performance issue for you. Can you go in a little more detail what activity1 is doing? Are you doing heavy network communication? Is it possible you can cache the store results?
in Actitity1 you define your WebView as:
private static WebView webView = null;
in onCreate() you only create it if it's null:
if(webView == null){
//create webview and load from network
}
Use this approach wisely as it may easly lead to memory leaks if you point to objects in other activities, or objects that may be kept alive (runnables, messages, etc.)
Related
In my app, there is a activity A, which it's a main activity, also there are several fragments inside A. When you click the images in one of fragments, it will start a new Activity B. When you click back button, i will call finish() to finish the activity and return to Activity A. But when returning to the Activity A, onCreate() of A is called again. Why onCreate() is called each time? As i know, it should be just called once, and then onStart() should be called.
From segment to the Activity B is as below:
Intent i = new Intent(_scontext, ProductListing.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_scontext.startActivity(i);
getActivity().overridePendingTransition(R.anim.push_out_to_left,R.anim.push_out_to_right);
When click back button in the Activity B, the code snippet is as following:
Intent _gobck = new Intent(_ctx,ProductDisplay.class);
startActivity(_gobck);
finish();
overridePendingTransition(R.anim.push_out_to_left,
R.anim.push_out_to_right);
What's wrong with the code? Am i missing anything?
You are starting the activity again. Remove the following code and it will work.
Intent _gobck = new Intent(_ctx,ProductDisplay.class);
startActivity(_gobck);
Since you already got your answer by #Rajitha Siriwardena but i just want to clear some of the points here,
As i know, it should be just called once, and then onStart() should
be called.
Above sentence is not a true first of all .
There is possibility to for your ActivityA to go in OnCreate even if you finish your ActivityB. If your ActivityB stay in foreground for a long time ,of-course your ActivityA will be in background in that case , so ultimately your Activity in onStop (remember not in onPause) and android Activity life cycle doc says, after onStop if your app want reach your Activity then it will goes in onCreate
So finish() ActivityB would work but there is no guarantee to your ActivityA called onCreate when you do so .
if you remove finish() from your backPress Activity will not be created and you don't need to write Intent it will manage it's back stack it self.
I have a quiet big application, and sometimes the user uses the HOME BUTTON to 'exit' the application or he receives a call etc. but when he clicks again on the icon, the application is resumed.
What I want is everytime somthing like this happens, the app restarts on the login activity (security process) before resuming the previous activity running before he exit the app.
When the HOME button is pushed, I believe your activity's onStop() and/or onPause() functions will be called. Override one of these methods and set a member variable to check if your activity was interrupted. Now override onResume() to check that variable to determine if you want to start your login activity.
Hopefully this idea gets you in the right direction.
You might also consider creating a super class that extends Activity and override the onStop()/onPause()/onResume() methods to exhibit this functionality. That way, all of your activities outside of your login activity can extend this class, allowing you to place the functionality that you desire in exactly one location.
Pass a Extra to any activity you call after login: intent.putExtra("isLogin", "Yes");
In every activity you call:
declare a field boolean isLogin;
In onCreate:
Intent sender = getIntent();
isLogin = sender.getStringExtra("isLogin","No") == "Yes";
In the onResume of every activity do this:
if(isLogin){
isLogin = false;
}else{
callActivityLogin();
}
Right now an activity gets destroyed when the BACK key is pressed. How can I make it just stop ( i.e. keep all the variables, etc. alive ), rather then be destroyed?
Thanks!
Why is it that you need to keep the variables alive? Given the established lifecycle of an Android application, I'm not sure that preventing the activity from being destroyed "just to keep the variables" makes sense.
Even if you stop the application without destroying it, there is always the chance that Android will kill it to free up memory. You will have to account for this in your code anyway, and so preventing the application from destroying doesn't save you from writing code.
Variables can be saved and restored relatively easily and quickly using SharedPreferences in your onPause() and onResume() methods. Unless you are storing a ton of data, preventing the application from destroying might not make much of a difference.
It sounds like you want to keep the variables in memory because you intend to return to this activity. Typically, you don't use the back button to navigate away from activities that you intend to come back to. Instead you would create an Intent and start a new activity. When you do this, Android places the current activity on the Back Stack calling onPause() and onStop(), which seems like exactly the sort of behavior you are looking for.
So if you still really want to prevent your activity from being destroyed (at least until Android decides it's using too much memory and kills it on it's own) you could always use Sagar's code and start a new activity in onBackPressed().
#Override
public void onBackPressed()
{
Intent intent = new Intent(this, Other.class);
startActivity(intent);
}
Just be certain that that is what you really want to do.
Simple one line
#Override
public void onBackPressed() {
mActivity.moveTaskToBack(true);
}
Pressing the BACK key triggers the onBackPressed callback method of Activity class. The default implementation of this callback calls the finish() method.
http://developer.android.com/reference/android/app/Activity.html#onBackPressed()
You can override this method to move the activity to background (mimick the action of pressing the HOME key.
eg:
#Override
public void onBackPressed() {
onKeyDown(KeyEvent.KEYCODE_HOME);
}
You could also instead consider moveTaskToBackground() mentioned here:
Override back button to act like home button
I have managed to work out exactly what you want: switch between 2 activities using Back button and keep them all not to be destroyed!
For example: you have 2 activities A & B. A will be started first, then A calls B. When B is loaded, user press Back button and switches back to activity A from B. From now B should not be destroyed and just goes to background, and when user starts activity B from A again, activity B will be brought to foreground, instead of being re-created again or created new instance! How to implement this:
1. Override onBackPressed() of activity B:
#Override
public void onBackPressed() {
Intent backIntent = new Intent(this, ActivityA.class);
backIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(backIntent);
}
2. On activity A, call activity B:
public void callActivityB() {
Intent toBintent = new Intent(this, ActivityB.class);
toBIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(toBintent);
}
remember to add flag: Intent.FLAG_ACTIVITY_REORDER_TO_FRONT when you call A&B.
This is similar to this question that was asked earlier.
Hope this helps!
N.S.
First of all, sorry for not answering the question, cause, I still have no optimal answer for it.
But, I really like when people start asking "what do you need this for". And, very rarely, the person who asked the question, really deserves this kind of question. I think not this time, but ok, this is not the issue...
Anyway, I will try to point out why some of us are convinced that
going from Activity A to Activity B(creating UI based on some data fetching) AND
going back from B to A(destroying all the created UI and/or fetched data in B) is sometimes a bad concept. Better solution would be to keep the stack as it is, so using something like finish() in Activity B, but keeping the Activity B in Pause state, so later when calling it again from Activity A - it just goes in onResume = nothing recreated in UI, no additional data fetching. The bonus of course is a fast and responsive UI, and the difference is really if you have a more complicated UI layout.
Just specify in the manifest for the activity as
android:persistent="true"
That should prevent your activity getting destroyed. To know more about this please refer to these below links which were answered by me
How to prevent call of onDestroy() after onPause()?
Prevent activity from being destroyed as long as possible
In the above posts I have explained in detail with a use case
My application starts with a welcome screen Activity, but that screen has an option to skip that screen altogether in future launches.
What's the proper Android way to do this? Initially, I just automatically detected the skipWelcome preference and switched to the 2nd activity from Welcome. But this had the effect of allowing the user to hit the back button to the welcome screen we promised never to show again.
Right now, in the Welcome activity, I read the preference and call finish() on the current activity:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean skipWelcome = preferences.getBoolean("skipWelcome", false);
if (skipWelcome) {
this.finish();
}
And then I implement onDestroy to move on to the next Activity:
#Override
public void onDestroy() {
super.onDestroy();
startActivity(new Intent(Welcome.this, StartFoo.class));
}
But this makes for some weird visual transitions. I'm starting to think that I need a base Activity that pops open Welcome only if proper, and then goes to StartFoo.
I can't comment on Mayra's answer or I would (not enough rep), but that's the correct approach.
Hidden in the Android documentation is this important phrase for Activity.startActivityForResult(),
"As a special case, if you call
startActivityForResult() with a
requestCode >= 0 during the initial
onCreate(Bundle
savedInstanceState)/onResume() of your
activity, then your window will not be
displayed until a result is returned
back from the started activity. This
is to avoid visible flickering when
redirecting to another activity."
Another important note is that this call does not block and execution continues, so you need to stop execution of the onCreate by returning
if (skipWelcome) {
// Create intent
// Launch intent with startActivityForResult()
return;
}
The final piece is to call finish immediately in the welcome activity's onActivityResult as Mayra says.
There are a few solutions to this.
Did you try just launching the activity and finishing? I vauguely remember that working, but I could be wrong.
More correctly, in if(skipWelcome) you can start the new activity for result, then when onActivityResult is called, immidiately finish the welcome activity.
Or, you can have your launcher activity not have a view (don't set content), and launch either the welcome activity or StartFoo.
The first Activity that loads in my application is an initialization activity, and once complete it loads a new Activity. I want to ensure if the user presses 'Back' they go straight to the Launcher, and not the initialization screen. Side note, is this even the best approach, or would this be better done with some kind of Intent Flag?
Is it correct to call finish() after calling startActivity() on the new activity?
onCreate() {
...
startActivity(new Intent(this, NextActivity.class));
finish();
...
}
I'm still taking in the whole 'Message Queue' method of doing things in Android, and my assumption is that calling startActivity() and then finish() from my first Activity's onCreate() will log each respective message in the message queue, but finish execution of onCreate() before moving on to starting the next Activity and finishing my first one. Is this a correct understanding?
Probably you should just use the noHistory flag on the activity in your manifest.xml