Android双击退出
思路:监听手机上的返回键,点击第一下记录,2s内点击第二下则退出,否则调用handler还原第一次点击的标志位
1 配置权限
2 onKey中调用
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.view.KeyEvent; import android.widget.Toast; public class DoubleClickExitHelper { private final Activity mActivity; private boolean isOnKeyBacking; private Handler mHandler; private Toast mBackToast; public DoubleClickExitHelper(Activity activity) { mActivity = activity; mHandler = new Handler(Looper.getMainLooper()); } /** * Activity onKeyDown事件 * */ public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode != KeyEvent.KEYCODE_BACK) { return false; } if(isOnKeyBacking) { mHandler.removeCallbacks(onBackTimeRunnable); if(mBackToast != null){ mBackToast.cancel(); } // 退出 //AppManager.getAppManager().AppExit(mActivity); //mActivity.finish(); AppExit(mActivity); return true; } else { isOnKeyBacking = true; if(mBackToast == null) { mBackToast = Toast.makeText(mActivity, "再按一次退出应用", 2000); } mBackToast.show(); mHandler.postDelayed(onBackTimeRunnable, 2000); return true; } } private Runnable onBackTimeRunnable = new Runnable() { @Override public void run() { isOnKeyBacking = false; if(mBackToast != null){ mBackToast.cancel(); } } }; /** * 退出应用程序 */ public void AppExit(Context context) { try { ActivityManager activityMgr= (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); activityMgr.restartPackage(context.getPackageName()); System.exit(0); } catch (Exception e) { } } }
相关推荐
huha 2020-10-16
xfcyhades 2020-11-20
sgafdsg 2020-11-04
Michael 2020-11-03
fengyeezju 2020-10-14
ziyexiaoxiao 2020-10-14
业余架构师 2020-10-09
OuNuo0 2020-09-29
moses 2020-09-22
Angelia 2020-09-11
qinxu 2020-09-10
刘炳昭 2020-09-10
Nostalgiachild 2020-09-07
Nostalgiachild 2020-08-17
leavesC 2020-08-14
一青年 2020-08-13
AndroidAiStudy 2020-08-07
ydc0 2020-07-30
绿豆饼 2020-07-28