想要完全退出应用,以前自己干掉自己的方法已经不能再用了。
那么如何做到完全退出所有Activity呢?
方法一、自己维护一个Activity任务栈
用集合保存所有Activity实例,退出应用时,遍历集合,逐个消灭
MyApplication.java1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| import java.util.LinkedList; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.app.Application; import android.content.DialogInterface; import android.content.Intent;
public class MyApplication extends Application { private List<Activity> mList = new LinkedList<Activity>(); private static MyApplication instance;
private MyApplication() { }
public synchronized static MyApplication getInstance() { if (instance == null) { instance = new MyApplication(); } return instance; }
// add Activity public void addActivity(Activity activity) { if(mList.contains(activity) return; mList.add(activity); } // 遍历集合,逐一finish // 最好从Activity栈底开始干掉 public void exit() { try { for (Activity activity : mList) { if (activity != null) activity.finish(); } } catch (Exception e) {} }
@Override public void onLowMemory() { super.onLowMemory(); System.gc(); } }
|
在每个Activity的onCreate方法中添加类似代码:
1 2 3 4 5 6 7 8 9 10 11
| public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MyApplication.getInstance().addActivity(this); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MyApplication.getInstance().addActivity(this); }
|
在需要退出程序的时候,调用:
1
| MyApplication.getInstance().exit();
|
此方法也可参考链接:http://maosidiaoxian.iteye.com/blog/1404725
方法二、使用广播
编写一个BaseActivity,此为所有Activity的基类,其内部注册一个退出Action的广播接收者,故而其所有的子Activity都会注册这个接收者。
当收到退出广播时,各个子Activity调用自己的finish()
,结束一生。
BaseActivity.java1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| public abstract class BaseActivity extends Activity { protected static final String ACTION_EXIT = "net.yrom.action.EXIT"; // 写一个广播的内部类,当收到动作时,结束activity private BroadcastReceiver exitReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { ((Activity)context)finish(); // 子Activity结束今生 } };
@Override public void onResume() { super.onResume(); // 在基类activity中注册广播 IntentFilter filter = new IntentFilter(ACTION_EXIT); registerReceiver(exitReceiver, filter); } // 子Activity调用这个方法来退出整个应用 public void close() { Intent intent = new Intent(ACTION_EXIT); sendBroadcast(intent);// 该函数用于发送广播 finish(); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(exitReceiver);
} }
|