I have two different activities. The first launches the second one. In the second activity, I call System.exit(0)
in order to force the application to close, bu
Say you have activity stack like A>B>C>D>E. You are at activity D, and you want to close your app. This is what you wil do -
In Activity from where you want to close (Activity D)-
Intent intent = new Intent(D.this,A.class);
intent.putExtra("exit", "exit");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
In your RootActivity (ie your base activity, here Activity A) -
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent.hasExtra("exit")) {
setIntent(intent);
}
}
@Override
protected void onResume() {
super.onResume();
if (getIntent() != null) {
if (("exit").equalsIgnoreCase(getIntent().getStringExtra(("exit")))) {
onBackPressed();
}
}
}
onNewIntent is used because if activity is alive, it will get the first intent that started it. Not the new one. For more detail - Documentation
I solved a similar problem: MainActivity starts BrowserActivity, and I need to close the app, when user press Back in BrowserActivity - not to return in MainActivity. So, in MainActivity:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "sm500_Rmt.MainActivity";
private boolean m_IsBrowserStarted = false;
and then, in OnResume:
@Override
protected void onResume() {
super.onResume();
if(m_IsBrowserStarted) {
Log.w(TAG, "onResume, but it's return from browser, just exit!");
finish();
return;
}
Log.w(TAG, "onResume");
... then continue OnResume. And, when start BrowserActivity:
Intent intent = new Intent(this, BrowserActivity.class);
intent.putExtra(getString(R.string.IPAddr), ip);
startActivity(intent);
m_IsBrowserStarted = true;
And it looks like it works good! :-)
You can also specify noHistory = "true" in the tag for first activity or finish the first activity as soon as you start the second one(as David said).
AFAIK, "force close" kills the process which hosts the JVM in which your application runs and System.exit() terminates the JVM running your application instance. Both are form of abrupt terminations and not advisable for normal application flow.
Just as catching exceptions to cover logic flows that a program might undertake, is not advisable.