In my project i move from main activity to activity A and from activity A to activity B. From activity B using home menu on toolbar i jump back to main activity. Now when i press back button application should exit but it opens the activity A again.
You should make use of the launch flags to manage your activities in the back stack. As far as I understood your scenario, I think you need to use FLAG_ACTIVITY_CLEAR_TOP for starting your main/home activity.
Read more about launch flags: https://developer.android.com/reference/android/content/Intent#FLAG_ACTIVITY_CLEAR_TOP.
Also, take a look this for more details on managing activity back stack on Android: https://developer.android.com/guide/components/activities/tasks-and-back-stack#ManagingTasks
Call the finish() method before starting the next activity to have it removed from the activity. Find more details and options here.
For Kotlin write this in your MainActivity :
override fun onBackPressed() {
moveTaskToBack(true)
exitProcess(-1)
}
For Java write this in your MainActivity :
#Override
void onBackPressed() {
moveTaskToBack(true)
exitProcess(-1)
}
Hope to it will work for you as good as for me
hey i write some code for you
Variables:
boolean backactivity = true;
CODE:
public boolean onOptionsItemSelected(MenuItem item){
if(backactivity==true)
{
finishActivity(1);
backactivity=false;
}else
{
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory( Intent.CATEGORY_HOME );
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
}
return true;
}
I have a menu when I click on a specific element of which the activity opens, but the user can quickly click menu iten 2 times, which will lead to the opening of the activity 2 times. How can I block the ability to press a button after the first press?
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.create) {
// start activity
}
return super.onOptionsItemSelected(item);
}
I know about setEnabled, but when I return to enabled activity, it remains false, and it seems inconvenient to save MenuItem and return its state. Anyone have any ideas how to do this optimally?
I found the best solution to this problem. To do this, add the FLAG_ACTIVITY_CLEAR_TOP flag to the Intent. Thanks to this, it will be impossible to create 2 activities.
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
In my app my first activity to launch is a login activity (A). When the login is successful another activity is launched (B), in doing so activity A is killed using finish(). This is to prevent the user being taken back to the login screen if they hit the back button, which works fine. Now when the app is closed from activity B using the home button and restored from the multitasking view the user comes back to activity B, which is great. However, when the user taps the back button in activity B the app closes and when the app is restored from the multitasking view, activity A is launched again when I actually want the behaviour clicking the home button gives and presenting the user with activity B.
Is there any way to do this?
You should simply add a check to your login activity, if the user is already signed in finish it and launch your B activity.
I'm really silly, just found my answer in one of the 'related' questions but it didn't come up when I created my question, oh well.
Here's what I did:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
Log.d("CDA", "onKeyDown Called");
onBackPressed();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onBackPressed() {
Log.d("CDA", "onBackPressed Called");
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
}
This essentially emulates what the home button would do in activity B.
How can I prevent the ActionBar back button (we gonna say ABBB) of my SecondActivity to recreate the MainActivitywhen clicked ?
I have a ListView in the MainActivity and it can be edited using the SecondActivity. The problem is that when the user presses the ABBB, the ListView is reset to default...
However, when the user clicks my OK button or presses physical back button, there is not any problem because I'm using finish();
#Override
public void onBackPressed() {
finish();
}
If I use this code... :
switch (item.getItemId()) {
case (android.R.id.home):
finish();
}
...there is the same problem because, I guess, this method is called after "Android's code".
How can I totally override Android ABBB's clicked code to set it to just call finish(); ?
The ideal scenario is, when are you in the SecondActivity (I take it that, this means that you are in Edit mode), and you press the device back button or ABBB, you show a subtle alert to the user saying "do they really want to dismiss the editing", or go ahead and apply the edit done as in the Contacts application.
So that being said, if all you require is to finish() the activity on press of ABBB, the code that you shown above should work fine (though you need to put return true; after finish()). It works for me. Try the below one in your activity.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed(); // or finish();
return true;
}
return super.onOptionsItemSelected(item);
}
I put onBackPressed(); because your ABBB with now imitate your device back button.
Or, you can set your parent activity's launch mode as -
android:launchMode="singleTop"
that will do all without changing anything.
Reference
I am sure this question has been asked number of times because I read a few. My client wants me to put a button into his app where users can click and exit. I have read this and found calling finish() will do it. But, finish is only closing the current running activity right? I have lot of activities so in this case I have to pass each and every activity's instance and finish them or make every activity into Singleton pattern.
I also got to know Activity.moveTaskToBack(true) can get you into the home screen. OK, this is not closing but backgrounding the process. So is this is effective?
Which method should I use to close the app completely? Any of above described or any other method/other usage of above methods?
The finishAffinity method, released in API 16, closes all ongoing activities and closes the app:
this.finishAffinity();
Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch.
Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.
Since API 21, you can use:
finishAndRemoveTask();
Finishes all activities in this task and removes it from the recent tasks list.
Alternatives:
getActivity().finish();
System.exit(0);
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
Process.sendSignal(Process.myPid(), Process.SIGNAL_KILL);
Intent i = new Intent(context, LoginActivity.class);
i.putExtra(EXTRA_EXIT, true);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(i);
Source: How to quit android application programmatically
Actually everyone is looking for closing the application via an onclick event, wherever may be activity...
Add this code to an onclick event:
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory( Intent.CATEGORY_HOME );
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
You can call System.exit(); to get out of all the acivities.
submit=(Button)findViewById(R.id.submit);
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
});
If you want to exit from your application, use this code inside your button pressed event:
public void onBackPressed() {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
#Override
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Exit Application?");
alertDialogBuilder
.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
It's way too easy. Use System.exit(0);
Accually there are two possible situations:
You may want to exit from the activity
Or you want to exit from the application
You can exit from the activity using following code:
var intent = new Intent(Intent.ActionMain);
intent.AddCategory(Intent.CategoryHome);
intent.SetFlags(ActivityFlags.NewTask);
startActivity(intent);
finish();
But this will not kill the underlying activities in the same application.
This will just minimize the application.
If you want to exit from application use the following code to end its process:
android.os.Process.killProcess(android.os.Process.myPid());
for mono development just use
process.KillProcess(Process.MyPid());
How about this.finishAffinity()
From the docs,
Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch.
Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.
android.os.Process.killProcess(android.os.Process.myPid());
this will clear Task(stack of activities) and begin new Task
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
System.exit(1);
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory( Intent.CATEGORY_HOME );
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
System.exit(1);
Use this Code it's much useful, and you can exit all of the activities.
#Override
public void onBackPressed() {
Intent homeIntent = new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory( Intent.CATEGORY_HOME );
homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
}
Achieving in Xamarin.Android:
public override void OnBackPressed()
{
MoveTaskToBack(true);
Process.KillProcess(Process.MyPid());
Environment.Exit(1);
}
put this one into your onClic:
moveTaskToBack(true);
finish()
Try this on a call. I sometimes use it in onClick of a button.
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
It instead of closing your app , opens the dashboard so kind of looks like your app is closed.
read this question for more clearity
android - exit application code
Use this.finishAffinity(); on that button instead of finish();
If it does not work then you can also try by adding android:noHistory="true" in your manifest and then finish your activity by uisng finish(); or finishAffinity();
Hope it helps....:)
Just call these two functions
finish();
moveTaskToBack(true);
Link this method to your quit/exit button
public void quitGame(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
finishAndRemoveTask();
} else {
finish();
}
}
ghost activity called with singletop and finish() on onCreate should do the trick
It works using only moveTaskToBack(true);
Instead of System.exit(1) Just use System.exit(0)
finish();
finishAffinity();
System.exit(0);
worked for me
If someone still wonders, for Xamarin.Android (in my case also Monogame running on it) the command FinishAndRemoveTask() on Activity does the job very well!
in the fragment
getActivity().finishAndRemoveTask();
in the Activity
finishAndRemoveTask();
just use the code in your backpress
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
If you are using EventBus (or really any other pub/sub library) in your application to communicate between activities you can send them an explicit event:
final public class KillItWithFireEvent
{
public KillItWithFireEvent() {}
public static void send()
{
EventBus.getDefault().post(new KillItWithFireEvent());
}
}
The only downside of this is you need all activities to listen to this event to call their own finish(). For this you can easily create shim activity classes through inheritance which just listen to this event and let subclasses implement everything else, then make sure all your activities inherit from this extra layer. The kill listeners could even add some extra functionality through overrides, like avoiding death on certain particular situations.
Just run the below two lines when you want to exit from the application
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
Just call this:
finishAffinity();
This can work I tried it too.
this.finishAffinity();
In Fragment use getActivity().finishAffinity(); and clear fragment binding without memory leaks