I have 4 activities. First one is splash activity and second is main menu activity and third activity is specific option from main activity and fourth one is result of third activity. I am using the noHistory="true" for second activity in manifest file. I have exit option in option menu for all activity. Once I exit from first three activity in app again I open app means it going launching application (there no resuming activities) but when I was exit from fourth activity then again I will open app means it show third activity instead of launch the app.
Exit code in option menu is
flag_activity_clear_top
flag_activity_no_history
but the previous activity is not close. How can we exit from all activities (including resuming activity)?
If I use the noHistory="true" attribute for third activity means it working properly, but when I press the home screen then again I reopen app it show splash activity instead of resuming activity. So I avoid to use the noHistory attribute in third activity.
Kindly please give solution for exit from all activities.
using Intent
Intent intent = new Intent(getApplicationContext(), FirstActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("FLAG_ACTIVITY_CLEAR_TOP", true);
startActivity(intent);
added in OnCreate your All Activity
if (getIntent().getBooleanExtra("FLAG_ACTIVITY_CLEAR_TOP", false)) {
finish();
}
Use sharePreference and check the value inside shared preference (inside onResume or OnStart()) every time you launch the application and navigate accordingly.
To close all Activities you can try call
finishAffinity();
This method finish current activity as well as all activities immediately below it in the current task that have the same affinity.
finishAffinity() can be called from Context i.e (Activity, Service etc)
If every time you close the application you want to close all Activities you just have to call finishAffinity in your OnDestroy() method or in onClick like
#Override
protected void onDestroy() {
super.onDestroy();
finishAffinity();
}
or
finishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finishAffinity();
}
});
Also example for menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.exit_item) {
finishAffinity();
}
return super.onOptionsItemSelected(item);
}
And you should NOT use any Flags for start or close an Activity, just call finishAffinity() where you wanna exit from application and finish all activities.
In this video you can see how it works https://youtu.be/L5w8mhB9aNk
Related
Pressing back button from the second activity returned to the first activity before without problems. I then updated to Android 7.
Then the whole app closed when pressing back button from the second activity.
I know that there are threads about this here and I have checked them all. Basically, they say that finish() should be avoided from the first activity.
I don't call finish(), so that is the problem here. It is difficult to solve, because it works like it should when I launch the app from Android studio.
It returns to the first activity from second. The problem occurs when the app is started by pressing its icon (not from Android studio).
Pressing back from the second activity closes down the whole app. How can I solve this? Here is some of my code:
Activity 1:
Intent glIntent = new Intent("astral.worldstriall.GLActivity");
glIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
The below code should be used in 2nd activity so that when u press back button it terminates the current activity(2nd activity) and goes back to previous activity
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
I think you just misused the Intent constructor. According to the documentation, you used this constructor Intent(String action). The one that you atually want should be this one Intent(Context packageContext, Class<?> cls).
In the first activity (therefore this being the instance of your first activity), you should write:
Intent glIntent = new Intent(this, astral.worldstriall.GLActivity.class);
glIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(glIntent);
For going first to second activity...
Intent i=new Intent(FirstActivity.this,SecondActivity.class);
startActivity(i);
Use below code for going in previous activity...
#Override
public void onBackPressed() {
super.onBackPressed();
Intent i=new Intent(SecondActivity.this, FirstActivity.class);
startActivity(i);
}
Hi in my code when user press back button from mainactivity he/she exit from the application but problem is when user again press application icon it resume the mainactivity where i left it..... i want to restart my app again when user click on application icon. Thanks in advance
///exit from app by pressing back button
public void onBackPressed() {
Log.i("HA", "Finishing");
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
You need this
public static final int FLAG_ACTIVITY_CLEAR_TASK
Added in API level 11
If set in an Intent passed to Context.startActivity(), this flag will cause any existing task that would be associated with the activity to be cleared before the activity is started. That is, the activity becomes the new root of an otherwise empty task, and any old activities are finished.
You should look here
There are three options:
1.You can override onResume() and put whatever is there in your onCreate() method inside it to do fresh restart everytime..
2.You can override onPause and kill the activity
onStop(); onCreate(getIntent().getExtras());
3.The best approach:
Alternatively you can also use http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_NO_HISTORY so that your activity is restarted everytime.
public static final int FLAG_ACTIVITY_NO_HISTORY
Added in API level 1 If set, the new activity is not kept in the
history stack. As soon as the user navigates away from it, the
activity is finished. This may also be set with the noHistory
attribute.
Constant Value: 1073741824 (0x40000000)
I have a question regarding android activity.
I have my first loginscreen(MainActivity) and from there go to Secondscreen, now when I am pressing escape button from the secondscreen I want to close the application(or android home screen) and next time open the application I want to start application with secondscreen.
i tried this code on my second screen but it does not working
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_ESCAPE)
{
//My logic here
return true;
}
return false;
}
First time when you use the application, Start with LoginScreen,
then call finish(). Also store a shared preference to know that, the
application is used atleast once(Logged in)
Since you finished the LoginScreen, when you press back button on SecondScreen, you will come to device home, not the LoginScreen.
Next time when you want to Start the application, check the sharedPreference whether the user is logged in, and finish the LoginScreen just at the start of onCreate
LoginScreenActivity:
onCreate(){
//check shared preference if logged in
if(yes){
startActivity(new Intent(Login.this, Second.class));
finish();
}else{
//do all the login here then,
//set sharedPreference
startActivity(new Intent(Login.this, Second.class));
finish();
}
}
What I assume you are trying something like below:
Frist installation#
LoginScreen>SecondScreen, when you press escape it will close entire app.
Second Time#
When you open app it will start from second screen instead loginScreen.
Solution
Phase1#
Store your login info in database or sharepreference when first time login has been made, and finish() loginscreen while opening second screen.
Phase2#
When you open second time your app, check your login info, if it is exists then redirect to second activity else open loginScreen.
When you start your second activity at that time finish the existing acitivity with finish()
example
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
finish();
This code will finish your current acitivity and when your press back button in second activity then the application gose close.
In log in activity call finish after starting second activity.
startActivity(i);
finish();
Now if u press back it should close the app and when u going to start app again the second activity will be visible.
There are two ways to do that:
make your log in activity with "noHistory=true" in android menifest activity definition.
<activity android:name="YOUR_FIRST_ACTIVITY"
android:label="FIRST_ACTIVITY"
android:noHistory="true" />
You can finish() the first activity at the time of starting second activity.
startActivity(SECOND_ACTIVITY_INTENT);
FIRST_ACTIVITY.this.finish();
Hope it will help you.
I have two activities, A and B. I have a button in A,when pressed starts a new intent to B.
However whenever I press the back button while in B, than click the button again is restarts Activity.I do not want to do that,I want it to resume Activity B.
Actually I am doing some networking in Activity B and I want to save unless the user wants to refresh.
How can I do it? Thanks in advance
Use
#Override
public void onBackPressed(){
moveTaskToBack(true);
}
Hope, It must help you
You need to Overrider the
onBackPressed
method and start there the activity like this:
#Override
public void onBackPressed() {
Intent intent = new Intent(this, activityA.class);
startActivityForResult(intent, PICK_CONTACT_REQ);
}
This sounds like you need to rethink your architecture. You say:
Actually I am doing some networking in Activity B and I want to save
unless the user wants to refresh.
If this is the case, you probably don't want to do your networking in ActivityB. Maybe you should start a Service from ActivityB to do the networking. The service and the activity can communicate with each other so that the activity can keep the user up-to-date about the state of the networking. If the user presses BACK in ActivityB, it can finish (as usual) and return to ActivityA. In this case, the Service is still managing the networking. When the user again starts ActivityB (from ActivityA), the new instance of ActivityB can communicate with the service to see if there is any networking going on, and if so it can get the current status of that networking or start it or stop it or whatever.
I guess I'm too late but I had a similar problem.
I had two activities A,B and a next button in A.
Whenever I tried to do: A->press next button ->B->press back button->A->press next button->B, B screen got destroyed when I pressed the back button. So when I came back to B for the second time it was a newly created B (all the information I had put in was gone).
So it was like A->B->A->new B when I just wanted to go back to the original B! :(
So what I did was, in activity B, I overrode the onBackPressed() function so it doesn't destroy the activity. I also set the flag so that if there is a A activity already running, it would just pull it up to the front instead of creating a new A activity.
#Override
public void onBackPressed() {
Intent intent = new Intent(getApplicationContext(), ActivityA.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
Then, for the onclicklistener function for the next button in activity A, I set the flags similarly.
public void onClickNextbutton(View v){
Intent intent = new Intent(getApplicationContext(), ActivityB.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
When a user presses the back button on an intent, the application should quit. How can I ensure the application quits when the back button is pressed?
In my Home Activity I override the "onBackPressed" to:
#Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
so if the user is in the home activity and press back, he goes to the home screen.
I took the code from Going to home screen Programmatically
Immediately after you start a new activity, using startActivity, make sure you call finish() so that the current activity is not stacked behind the new one.
EDIT
With regards to your comment:
What you're suggesting is not particularly how the android app flow usually works, and how the users expect it to work. What you can do if you really want to, is to make sure that every startActivity leading up to that activity, is a startActivityForResult and has an onActivityResult listener that checks for an exit code, and bubbles that back. You can read more about that here. Basically, use setResult before finishing an activity, to set an exit code of your choice, and if your parent activity receives that exit code, you set it in that activity, and finish that one, etc...
A better user experience:
/**
* Back button listener.
* Will close the application if the back button pressed twice.
*/
#Override
public void onBackPressed()
{
if(backButtonCount >= 1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
The app will only exit if there are no activities in the back stack. SO add this line in your manifest android:noHistory="true" to all the activities that you dont want to be back stacked.And then to close the app call the finish() in the OnBackPressed
<activity android:name=".activities.DemoActivity"
android:screenOrientation="portrait"
**android:noHistory="true"**
/>
Why wouldn't the user just hit the home button? Then they can exit your app from any of your activities, not just a specific one.
If you are worried about your application continuing to do something in the background. Make sure to stop it in the relevant onPause and onStop commands (which will get triggered when the user presses Home).
If your issue is that you want the next time the user clicks on your app for it to start back at the beginning, I recommend putting some kind of menu item or UI button on the screen that takes the user back to the starting activity of your app. Like the twitter bird in the official twitter app, etc.
Use onBackPressedmethod
#Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
This will solve your issue.
First of all, Android does not recommend you to do that within the back button, but rather using the lifecycle methods provided. The back button should not destroy the Activity.
Activities are being added to the stack, accessible from the Overview (square button since they introduced the Material design in 5.0) when the back button is pressed on the last remaining Activity from the UI stack. If the user wants to close down your app, they should swipe it off (close it) from the Overview menu.
Your app is responsible to stop any background tasks and jobs you don't want to run, on onPause(), onStop() and onDestroy() lifecycle methods. Please read more about the lifecycles and their proper implementation here: http://developer.android.com/training/basics/activity-lifecycle/stopping.html
But to answer your question, you can do hacks to implement the exact behaviour you want, but as I said, it is not recommended:
#Override
public void onBackPressed() {
// make sure you have this outcommented
// super.onBackPressed();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
To exit from an Android app, just simply use.
in your Main Activity, or you can use Android manifest file to set
android:noHistory="true"
finish your current_activity using method finish() onBack method of your current_activity
and then add below lines in onDestroy of the current_activity for Removing Force close
#Override
public void onDestroy()
{
android.os.Process.killProcess(android.os.Process.myPid());
super.onDestroy();
}
I modified #Vlad_Spays answer so that the back button acts normally unless it's the last item in the stack, then it prompts the user before exiting the app.
#Override
public void onBackPressed(){
if (isTaskRoot()){
if (backButtonCount >= 1){
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}else{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}else{
super.onBackPressed();
}
}
you can simply use this
startActivity(new Intent(this, Splash.class));
moveTaskToBack(true);
The startActivity(new Intent(this, Splash.class)); is the first class that will be lauched when the application starts
moveTaskToBack(true); will minimize your application
Add this code in the activity from where you want to exit from the app on pressing back button:
#Override
public void onBackPressed() {
super.onBackPressed();
exitFromApp();
}
private void exitFromApp() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}