App中连续点击Back键退出应用

   现在的App就用越来越人性化了,为了满足用户的体验欲望,从各个方面都进行了仔细处理。比如我们点击第一次点击Back键的时候,会温馨提示“再按一次返回键退出应用”等,今天 就记录下自己在项目中写的这个小功能:

首先写个工具类:

public class DoubleClickExitApp {

   private Context mcontext;
   /**是否是再次点击back*/
   private boolean isOnKeyBack;
   private Handler mHandler;
   /**退出提示Toast*/
   private Toast mExitToast;

   public DoubleClickExitApp(Context context) {
      this.mcontext = context;
      this.mHandler = new Handler(Looper.getMainLooper());
   }

   /**所在Activity中的点击返回事件处理*/
   public boolean onKeyDown(int keyCode, KeyEvent event) {
      if(keyCode != KeyEvent.KEYCODE_BACK) {//如果不是点击的返回键,则返回false
         return false;
      }
      if(isOnKeyBack) {
         mHandler.removeCallbacks(onBackExitRunnable);
         if(mExitToast != null){
            mExitToast.cancel();
         }
         /**直接退出*/
         AppManager.getAppManager().AppExit(mcontext);
         return true;
      } else {
         isOnKeyBack = true;
         if(mExitToast == null) {
            mExitToast = Toast.makeText(mcontext, "再按一次返回键退出应用", Toast.LENGTH_SHORT);
         }
         mExitToast.show();
         mHandler.postDelayed(onBackExitRunnable, 2000);
         return true;
      }
   }

   private Runnable onBackExitRunnable = new Runnable() {

      @Override
      public void run() {
         isOnKeyBack = false;
         if(mExitToast != null){
            mExitToast.cancel();
         }
      }
   };
}
然后在对应的Activity或是主页面中直接调用:
public class MainActivity extends Activity{
     private DoubleClickExitApp mDoubleClickExitApp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         mDoubleClickExitApp = new DoubleClickExitApp(this);
} @Override protected void onDestroy() { super.onDestroy(); } /**在处理onKeyDown事件中调用我们写的工具类方法就可以*/ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { return mDoubleClickExitApp.onKeyDown(keyCode, event); }else{
          return super.onKeyDown(keyCode, event);
       }
 
    }




郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。