Reputation: 5717
it's not recommended to exit application directly, so the point is to finish all activities so everything goes to the background and user returns to the home screen. My problem is that I have main activity, which is always launched with flags Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP and it launches another activity, where I want to place the exit button. In order to get everything to the background I have to finish both current and main activity. I though that launching main activity with those flags and extra info that it should exit would do the trick, but the extras delivered with the intent do not reach main activity - it still gets the intent that was used by android to launch the application.
In other words, I tried something like:
// Exit's onClick:
Intent intent = new Intent(someContext, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("exit", true);
context.startActivity(intent);
currentActivity.finish();
// MainActivity onCreate:
Bundle extras = getIntent().getExtras();
if (extras != null)
{
// application never reach this point
boolean exit = extras.getBoolean("exit");
if (exit)
{
finish();
return;
}
}
The extras are delivered. How can I get it working?
Thanks
Upvotes: 1
Views: 3674
Reputation: 1856
Simple, make a class and put a static variable and function like this:
public static boolean isExit = false;
public static boolean CheckExit() {
return isExit;
}
public static void setisExit(boolean b)
{
isExit = b;
}
And in your Main Activity put YourClassName.setisExit(false);
is will make sure isExit
value is false when application start again.
To Exit:
Put this in your OnClick
method:
YourClassName.setisExit(true);
finish();
And put this in first line of OnResume
method of every activity:
if(YourClassName.CheckExit()) {
finish();
return super.onResume();
}
By doing this every time a Activity resume is check the isExit
value and if true then exit.
You can check my app E Player
on google play. I implemented this method and its working fine
Upvotes: 0
Reputation: 114
I don't know if it is the best solution, but work to me:
On Event Listener:
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
Upvotes: 0
Reputation: 780
System.Exit(0);
//You can use that to exit the entire application, not just one activity
Upvotes: 1
Reputation: 966
When setting this 2 flags MainActivity will not reach onCreate() if it is still in the stack. This would call onNewIntent().
Check this 2 links for more information:
http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP
Upvotes: 3
Reputation: 3479
Set Launch Mode of MainActivity
as "SingleTop"
in AndroidManifest.xml
file as follows:
android:launchMode="singleTop"
Upvotes: 0