轉載:http://blog.sina.com.cn/s/blog_6f6ea9d90101a8ad.html
1.ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
manager.killBackgroundProcesses(package);
不行
2.android.os.Process.killProcess(android.os.Process.myPid());
也不行
3.manager.restartPackage(package);
還是不行
4.
Intent MyIntent = new Intent(Intent.ACTION_MAIN);
MyIntent.addCategory(Intent.CATEGORY_HOME);
startActivity(MyIntent);
finish();
這個只是退回到桌面,如果打開多個Activity關閉重新打開也會有問題,還是還是不行
看到有說廣播機制,發現是個好東東,能徹底解決這個問題,廢話不說看代碼:
- public abstract class EnterActivity extends BaseActivity {
- ...
- // 寫一個廣播的內部類,當收到動作時,結束activity
- private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- unregisterReceiver(this); // 這句話必須要寫要不會報錯,不寫雖然能關閉,會報一堆錯
- ((Activity) context).finish();
- }
- };
- @Override
- public void onResume() {
- super.onResume();
- // 在當前的activity中註冊廣播
- IntentFilter filter = new IntentFilter();
- filter.addAction(Attribute.PAGENAME);
- registerReceiver(this.broadcastReceiver, filter); // 註冊
- }
- public void close() {
- Intent intent = new Intent();
- intent.setAction(Attribute.PAGENAME); // 說明動作
- sendBroadcast(intent);// 該函數用於發送廣播
- finish();
- }
- ...
- }
別人寫的缺了個地方(unregisterReceiver)這個必須要加,找了個最簡單的方法