1:定义一个用于管理Activity的类。
/* * 用于管理Activity */ public class SysApp extends Application{ private List<Activity> mList=new LinkedList<Activity>(); private static SysApp instance; private SysApp(){} public synchronized static SysApp getInstance(){ if(null==instance){ instance=new SysApp(); } return instance; } public void addActivity(Activity activity){ mList.add(activity); } public void exit(){ try{ for(Activity activity:mList){ if(null!=activity){ activity.finish(); activity.overridePendingTransition( android.R.anim.fade_in, android.R.anim.slide_out_right); } } }finally{ System.exit(0); } } public void onLowMemory(){ super.onLowMemory(); System.gc(); } }
2:在每个Activity的onCreate方法中:将当前的Activity加入到List中。
SysApp.getInstance().addActivity(this);
3:检测用户两次按回退键的动作:
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode==KeyEvent.KEYCODE_BACK){ if ((System.currentTimeMillis() - mExitTime) > 2000) { Toast.makeText(MainActivity.this, "再按一次回退键退出系统!", Toast.LENGTH_SHORT).show(); mExitTime = System.currentTimeMillis(); } else { //退出系统 SysApp.getInstance().exit(); } } return true; }