I have created an application that has multiple pages and navigation from one to another represents a crucial flow. I don't want the user to be able to press the back button and escape the activity without first warning him and then finally deleting all stack trace such that when the activity is launched again it starts afresh.
As of yet I have been using something similar to the function below :
#Override
public void onBackPressed()
{
this.finish();
Intent int1= new Intent(this, Home.class);
int1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(int1);
super.onBackPressed();
}
But sometimes when after quitting the application when I launch it again it restarts from some random page or the one from where I quit the application (basically not the home screen from where it is expected to start)
I cannot think of a cleaner way to quit the application other than clearing all the previous activity flags as described in the code.
Any help on the above is appreciated!
EDIT :
Anytime during the flow of my activity if the user presses the back button, I want the control to be thrown back to the main page (clearing all the previous activity stack traces). Such that in case someone re-lanches the application it will re start normally from the main page.
You don't need any of this custom code in onBackPressed(). All you need to do is add this to all of your <activity> definitions in the manifest (except the root activity):
android:noHistory="true"
This ensures that none of your activities (expect the root activity) is recorded in the back stack. When the user clicks the BACK key, it will just return to the root activity.
Another benefit of this is that if the user leaves your app (by clicking HOME or by pulling down the notification bar and clicking on a notification, when he returns to your app it will also just return to your root activity.
Anytime during the flow of my activity if the user presses the back
button, I want the control to be thrown back to the main page
(clearing all the previous activity stack traces).
This can be done just by finishing all the activities as they move forward, except the MainActivity.
Such that in case someone re-lanches the application it will re start
normally from the main page.
Is it like if user is in Activity_5 and uses Home Button and relaunches the app again, MainActicity must appear?
IF so, you can call finish() in onPause() of every Activity except MainActivity
EDIT:
Might not be the perfect solution, but this is what I did to achieve exactly the same(logout in my application):
OnBackPressed() in any activity updates a boolean shared preference say backPressed to true and in onResume() of all the Activities, except MainActivity check its value and finish if true.
#Override
protected void onResume() {
super.onResume();
SharedPreferences mSP = getSharedPreferences(
"your_preferences", 0);
if (mSP .getBoolean("backPressed", false)) {
finish();
}
}
Back Button is used to go back to the previous activity. So i would not override the back button to clear activity stack. I suggest you use a Action Bar for this purpose. Navigate to Home Screen of the application using the application icon.
http://developer.android.com/guide/topics/ui/actionbar.html
Also check this link and comments below the answer by warrenfaith
android - onBackPressed() not working for me
#Override
public void onBackPressed()
{
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
you can use that code, it's work for me!
Related
Normally when the back button is clicked it goes to the previous activity and if the current activity is the first activity, the application closes.
I have a splash screen (that is logically my first activity) and then the menu activity loads.
I want to close the program when the back button is pressed on my menu activity (as if it is the first activity) and avoid going back to the splash screen again, but I know that I should not exit the program.
I was wondering what is the functionality of back button on the first activity?
does it put the program to pause?
Avoid splash screens !
Instead of using your splash as the main activity, use menu activity as the main one, and in onCreate() chain off the splash activity, which will close and disappear forever.
When new Activity is launched from first Activity, first Activity is executed until onStop() method, then it stops and waits for relaunch, unless you killed it by calling .finish(), in that case launched Activity becomes first Activity and back button will minimize application on back button press. In order to control what application does on back button press you can override this method in your Activities and implement your own custom behaviour:
#Override
public void onBackPressed() {
super.onBackPressed()
}
Very good example of how lifecycle of Fragments/Activities work can be seen in picture below:
Hope this helps. Good luck.
While you are on the SplashScreen, on the method calling your menu activity I assume you are doing something like startActivity (new Intent (this, MenuActivity.class)); in Java or startActivity(Intent(this, MenuActivity::class.java)) for Kotlin just after that call finish() this will remove your SplashScreen from the back stack
add this attribute to your splash activity (in manifest):
android:excludeFromRecents="true"
pressing back in per activity, transfer control to prev activity in stack (back stack) that not excluded from "Recents".
Basicly, i have 3 activities in my app. call them A,B and Login, A and B shows the user very sensitive data. a legit flow has the form of launch->Login->A->B->A->B...->A->quit what i really want is that if for some reason the app got to the background ( by pressing back or home or whatever ) while it was still on A, or on B, then no metter what way the app relaunches ( or traced in some way including by the long home press menu ) it would not show A or B content. he can see either the login page content, or nothing at all.
noHistory is almost what i was looking for, but isnt a good solution since i want to allow intuative navigation from A to B and back to A. so how is it done?
Check out the "clearTaskOnLaunch" Activity attribute.
When the value is "true", every time users start the task again, they
are brought to its root activity regardless of what they were last
doing in the task and regardless of whether they used the Back or Home
button to leave it.
try the following pseudo:
public A extends Activity
{
boolean just_launched = true;
void onPause()
{
just_launched = false;
}
void onResume()
{
if (!just_launched)
finish();
}
}
When the BACK button is pressed on the phone, I want to prevent a specific activity from returning to its previous one.
Specifically, I have login and sign up screens, both start a new activity called HomeScreen when successful login/signup occurs. Once HomeScreen is started, I want to prevent the users from being able to return to the login or sign up screens by pressing the BACK key.
I tried using Intent.FLAG_ACTIVITY_NO_HISTORY, but since the application has Facebook integration, when the 'Login with Facebook' is used, Facebook should return to the initial login screen, therefore I should keep a history of these activities.
I thought of overriding the behaviour of the BACK button on HomeScreen to directly finish an application when the button is pressed and I used
#Override
public void onBackPressed() {
finish();
}
but that also does not work.
My suggestion would be to finish the activity that you don't want the users to go back to. For instance, in your sign in activity, right after you call startActivity, call finish(). When the users hit the back button, they will not be able to go to the sign in activity because it has been killed off the stack.
Following solution can be pretty useful in the usual login / main activity scenario or implementing a blocking screen.
To minimize the app rather than going back to previous activity, you can override onBackPressed() like this:
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
moveTaskToBack(boolean nonRoot) leaves your back stack as it is, just puts your task (all activities) in background. Same as if user pressed Home button.
Parameter boolean nonRoot - If false then this only works if the activity is the root of a task; if true it will work for any activity in a task.
I'm not sure exactly what you want, but it sounds like it should be possible, and it also sounds like you're already on the right track.
Here are a few links that might help:
Disable back button in android
MyActivity.java =>
#Override
public void onBackPressed() {
return;
}
How can I disable 'go back' to some activity?
AndroidManifest.xml =>
<activity android:name=".SplashActivity" android:noHistory="true"/>
There are two solutions for your case, activity A starts activity B, but you do not want to back to activity A in activity B.
1. Removed previous activity A from back stack.
Intent intent = new Intent(activityA.this, activityB.class);
startActivity(intent);
finish(); // Destroy activity A and not exist in Back stack
2. Disabled go back button action in activity B.
There are two ways to prevent go back event as below,
1) Recommend approach
#Override
public void onBackPressed() {
}
2)Override onKeyDown method
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK) {
return false;
}
return super.onKeyDown(keyCode, event);
}
Hope that it is useful, but still depends on your situations.
Since there are already many great solutions suggested, ill try to give a more dipictive explanation.
How to skip going back to the previous activity?
Remove the previous Activity from Backstack. Simple
How to remove the previous Activity from Backstack?
Call finish() method
The Normal Flow:
All the activities are stored in a Stack known as Backstack.
When you start a new Activity(startActivity(...)) then the new Activity is pushed to top of the stack and when you press back button the Activity is popped from the stack.
One key point to note is that when the back button is pressed then finish(); method is called internally. This is the default behavior of onBackPressed() method.
So if you want to skip Activity B?
ie A<--- C
Just add finish(); method after your startActvity(...) in the Activity B
Intent i = new Intent(this, C.class);
startActivity(i);
finish();
finish() gives you method to close current Activity not whole application. And you better don't try to look for methods to kill application. Little advice.
Have you tried conjunction of Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NO_HISTORY? Remember to use this flags in Intent starting activity!
Put finish() just after
Intent i = new Intent(Summary1.this,MainActivity.class);
startActivity(i);
finish();
If you don't want to go back to all the activities on your application, you can use
android:launchMode="singleTask"
Learn more here: http://developer.android.com/guide/topics/manifest/activity-element.html
paulsm4's answer is the correct one. If in onBackPressed() you just return, it will disable the back button. However, I think a better approach given your use case is to flip the activity logic, i.e. make your home activity the main one, check if the user is signed in there, if not, start the sign in activity. The reason is that if you override the back button in your main activity, most users will be confused when they press back and your app does nothing.
This method is working fine
Intent intent = new Intent(Profile.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
#Override
public void onBackPressed() {
}
When you create onBackPressed() just remove super.onBackPressed();and that should work
Just override the onKeyDown method and check if the back button was pressed.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
//Back buttons was pressed, do whatever logic you want
}
return false;
}
Put
finish();
immediately after
ActivityStart
to stop the activity preventing any way of going back to it.
Then add
onCreate(){
getActionBar().setDisplayHomeAsUpEnabled(false);
...
}
to the activity you are starting.
AndroidManifest.xml
<activity
android:name=".welcome.SplashActivity"
android:noHistory="true" // just add this line
android:exported="true">
</activity>
I have two activities A and B. What I want is to show activity A as an intro, the user will be unable to navigate back to it. Is there some flag I can set to activity A to do this? Can I block the back button for one activity only? Activity A is of course my main activity which automatically starts activity B after some "hard work".
Best regards.
you do not need to block the back button, but just call finish() on your A activity after firing an intent to start B. Back button pops the previous activity from activity stack and it won't be able to pop A if it is already finished.
For this you don't need to block the Back button. Simply, start the second Activity and quit the first one. And now if user presses the Back, they will be taken to the Android home screen not on your apps home screen.
Updates: By the way if you want to intercept the Back button for any reason, simply override the onBackPressed() method of Activity class. See this for details.
Never override the functionality of a hardware button.
You should call finish() in Activity A right after starting Activity B (calling the Intent).
it works but the application terminates and i'm redirected to android's applications screen. I would like to stay in activity B if back button is pressed, i don't want to exit the app. here's is what i got :
public void startProgram(Context context){
Intent intent = new Intent(context, ActivityB.class);
startActivity(intent);
finish();
}
How can I kill all the Activities of my application?
I tried using this.finish() but it just kills one Activity.
In fact, I would like when the user touches the back button (in only one of the activities), the application to do the same as if he pressed the Home button.
You can set android:noHistory="true" for all your activities at AndroidManifest.xml. Hence they will not place themselves onto history stack and back button will bring you to the home screen.
This has been discussed many times before. Essentially there's no easy way, and there's not supposed to be. Users press Home to quit your app (as you have pointed out).
Override the onBackPressed method, and do what happens when they press the home button. It's not really closing all the activities but what you're asking is that the back press in a certain activity emulates the home button.
#Override
public void onBackPressed() {
Intent i = new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
}
Placing that in an activity will go home when you press back. Note that the original implementation of the onBackPressed method includes a call to super, it's removed on purpose. I know this question is super old, but he's explicitly asking something else
To kill all the activities, use these code on onBackPressed.
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount()>0) {
getFragmentManager().popBackStackImmediate();
} else {
finishAffinity();
System.exit(0);
}
}