按两次返回键退出程序和长按返回键退出程序

按两次返回键退出程序:

public class Exit {

[java]  view plain copy
  1. private boolean isExit = false;  
  2. private Runnable task = new Runnable() {  
  3.     @Override  
  4.     public void run() {  
  5.         isExit = false;  
  6.     }  
  7. };  
  8.   
  9. public void doExitInOneSecond() {  
  10.     isExit = true;  
  11.     HandlerThread thread = new HandlerThread("doTask");  
  12.     thread.start();  
  13.     new Handler(thread.getLooper()).postDelayed(task, 1000);  
  14. }  
  15.   
  16. public boolean isExit() {  
  17.     return isExit;  
  18. }  
  19.   
  20. public void setExit(boolean isExit) {  
  21.     this.isExit = isExit;  
  22. }  

Activity:

[java]  view plain copy
  1. public class Back2FinishAppActivity extends Activity {  
  2.     Exit exit = new Exit();  
  3.   
  4.     /** Called when the activity is first created. */  
  5.     @Override  
  6.     public void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.main);  
  9.     }  
  10.       
  11.       
  12.       
  13.     @Override    
  14.       public boolean onKeyDown(int keyCode, KeyEvent event) {    
  15.         if (keyCode == KeyEvent.KEYCODE_BACK) {    
  16.                 pressAgainExit();    
  17.                 return true;    
  18.                 }    
  19.       
  20.           return super.onKeyDown(keyCode, event);    
  21.       }    
  22.         
  23.     private void pressAgainExit() {    
  24.             if (exit.isExit()) {    
  25.                 finish();    
  26.             } else {    
  27.                 Toast.makeText(getApplicationContext(), "再按一次退出程序",    
  28.                         Toast.LENGTH_SHORT).show();    
  29.                 exit.doExitInOneSecond();    
  30.             }    
  31.         }    
  32. }  


长按返回键退出程序:

[java]  view plain copy
  1. public boolean dispatchKeyEvent(KeyEvent event)    
  2.     {    
  3.         int keyCode=event.getKeyCode();    
  4.         switch(keyCode)    
  5.         {    
  6.             case KeyEvent.KEYCODE_BACK: {    
  7.                  if(event.isLongPress())    
  8.                  {    
  9.                      this.stopService(intent);    
  10.                      System.exit(0);    
  11.                      return true;    
  12.                  }else    
  13.                  {    
  14.                      return false;    
  15.       
  16.                  }    
  17.             }      
  18.         }    
  19.         return super.dispatchKeyEvent(event);    
  20.             
  21.     }  

你可能感兴趣的:(java,Class)