Implement full exit program method in android (exit all activity)
- 2020-06-19 11:44:43
- OfStack
This is a problem that many, many people encounter. I have tried many methods, but none of them work well.
Such as:
System.exit(0);
I can't.
What else jumps to the first activity, while clearing all activity at the top of the stack, and finally finish(); Still no. I don't know why.
Here's one of my own that works really well.
Principle: Each activity registers a broadcast receiver to receive broadcasts that turn off activity. When the program needs to exit, send a radio to turn off activity, so that all activity will receive, and then all activity will be finish.
package com.example.exitsystem;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
/**
* all activity You inherit this class, and you register a broadcast,
* You can send a broadcast when you need to exit the system completely,
* action for com.example.exitsystem.system_exit (Custom),
* This allows you to exit all at any time activity the
* @author LinZhiquan
*
*/
public class SuperActivity extends Activity {
/** radio action */
public static final String SYSTEM_EXIT = "com.example.exitsystem.system_exit";
/** The receiver */
private MyReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Register the broadcast to exit the program
IntentFilter filter = new IntentFilter();
filter.addAction(SYSTEM_EXIT);
receiver = new MyReceiver();
this.registerReceiver(receiver, filter);
}
@Override
protected void onDestroy() {
// Remember to cancel your broadcast registration
this.unregisterReceiver(receiver);
super.onDestroy();
}
private class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
finish();
}
}
}
package com.example.exitsystem;
import android.os.Bundle;
/**
* ordinary activity . inheritance SuperActivity
* @author LinZhiquan
*
*/
public class MainActivity extends SuperActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Send a broadcast when you need to exit the program.
Intent intent = new Intent();
intent.setAction(SuperActivity.SYSTEM_EXIT);
sendBroadcast(intent);