网上有很多实现的代码,实现起来也不难,这边提供一个我认为比较好的用户体验的代码:
首先在要退出的Activity中添加代码: 代码为全局代码
private long exitTime = 0; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){ if((System.currentTimeMillis()-exitTime) > 2000){ Toast.makeText(getApplicationContext(), "再按一次后退键退出程序", Toast.LENGTH_SHORT).show(); exitTime = System.currentTimeMillis(); } else { SysApplication.getInstance().exit(); } return true; } return super.onKeyDown(keyCode, event); }
这句代码的作用是关闭整个程序的Acitivity,为此,我们需要将程序中的Acitvity加入到堆栈中进行管理
主要的代码如下:
先声明一个类:用于管理Acitivity
package com.jinbi.app.ui; import java.util.LinkedList; import java.util.List; import android.app.Activity; import android.app.Application; public class SysApplication extends Application { private List<Activity> mList = new LinkedList<Activity>(); private static SysApplication instance; private SysApplication() { } public synchronized static SysApplication getInstance() { if (null == instance) { instance = new SysApplication(); } return instance; } // add Activity public void addActivity(Activity activity) { mList.add(activity); } public void exit() { try { for (Activity activity : mList) { if (activity != null) activity.finish(); } } catch (Exception e) { e.printStackTrace(); } finally { System.exit(0); } } @Override public void onLowMemory() { super.onLowMemory(); System.gc(); } }为了将Activity添加到堆栈中,为此我们需要在每个Acitivity的onCreate函数中加入一句以下代码:
SysApplication.getInstance().addActivity(this);
SysApplication.getInstance().exit();