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

Android连续点击两次Back键退出程序

时间:2014-09-17 15:33:53      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:android   private   public   method   程序   

     思路1:记录上次点击的时间,与本次点击的时间比较,当两次时间间隔小于一定值时,退出,否则提示“再按一次退出程序”,同时更新上次点击时间

     
private long firstTime = 0;  
   @Override  
public boolean onKeyUp(int keyCode, KeyEvent event) {  
       // TODO Auto-generated method stub  
       switch(keyCode)  
       {  
       case KeyEvent.KEYCODE_BACK:  
            long secondTime = System.currentTimeMillis();   
             if (secondTime - firstTime > 2000) {                                         //如果两次按键时间间隔大于2秒,则不退出  
                 Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();   
                 firstTime = secondTime;//更新firstTime  
                 return true;   
             } else {                                                    //两次按键小于2秒时,退出应用  
            System.exit(0);  
             }   
           break;  
       }  
     return super.onKeyUp(keyCode, event);  
   }

思路2:开线程延时处理

private int mBackKeyPressedTimes = 0;  
  
        @Override  
        public void onBackPressed() {  
                if (mBackKeyPressedTimes == 0) {  
                        Toast.makeText(this, "再按一次退出程序 ", Toast.LENGTH_SHORT).show();  
                        mBackKeyPressedTimes = 1;  
                        new Thread() {  
                                @Override  
                                public void run() {  
                                        try {  
                                                Thread.sleep(2000);  
                                        } catch (InterruptedException e) {  
                                                e.printStackTrace();  
                                        } finally {  
                                                mBackKeyPressedTimes = 0;  
                                        }  
                                }  
                        }.start();  
                        return;  
                      else{  
                               this.activity.finish();  
                            }  
                }  
                super.onBackPressed();  
        }

Android连续点击两次Back键退出程序

标签:android   private   public   method   程序   

原文地址:http://8988940.blog.51cto.com/8978940/1553629

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