码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2015-05-21 15:37:27      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:android开发   退出应用   工具类   

   现在的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);
       }
 
    }




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

标签:android开发   退出应用   工具类   

原文地址:http://blog.csdn.net/true100/article/details/45892073

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!