Right now every decent Android developer probably thinks I lost my mind. That’s true: there is no need for exit buttons in our Android apps. This behaviour is just as Google wants it to be. And that’s why there is no easy way to kill the app from the activity which is not the last standing.
As usually, there is a workarround. Please do not use it to implement close buttons in your apps.
This is something for special occasions. I use this method to kill an app, if a user decides to do not pay for an expired subscription.
Instruction for an app kill
It’s fairly simple, if you understand Android activities flow.
- To kill the app you basically need to “`finish()“` all the activities that the app had opened before.
- If we finish the first activity that our app opened on the startup, the app closes.
- To do this from any “`Activity“` we need to open our first “`Activity“` with the flag “`FLAG_ACTIVITY_CLEAR_TOP“` and some extra that will inform our first “`Activity“` to “`finish()“` itself on the startup.
Here is how the killing method would look like:
protected void onFinishClick() { Intent intent = new Intent(this, ActivityA.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(ActivityA.SHOULD_FINISH, true); startActivity(intent); }
This is how the first “`Activity“` kills itself when needed.
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_a); ButterKnife.inject(this); if (getIntent().getBooleanExtra(SHOULD_FINISH, false)) { finish(); } }
That’s it, the app should close and get us to the home screen.
Here is the github repository with the sample app demonstrating this technique.
Cheers!