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

时间:2022-05-30 06:09:27

以上两个功能主要是参考了一下博客的:

http://blog.csdn.net/chenshijun0101/article/details/7682210

http://blog.csdn.net/winlinking/article/details/6596455

方法一:

按两次返回键退出程序:

Activity:

Android_按两次返回键退出程序和长按返回键退出程序
public class Back2FinishAppActivity extends Activity {
Exit exit = new Exit(); /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
} @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
pressAgainExit();
return true;
} return super.onKeyDown(keyCode, event);
} private void pressAgainExit() {
if (exit.isExit()) {
finish();
} else {
Toast.makeText(getApplicationContext(), "再按一次退出程序",
Toast.LENGTH_SHORT).show();
exit.doExitInOneSecond();
}
}
}
Android_按两次返回键退出程序和长按返回键退出程序

辅助类Exit.java

Android_按两次返回键退出程序和长按返回键退出程序
private boolean isExit = false;
private Runnable task = new Runnable() {
@Override
public void run() {
isExit = false;
}
}; public void doExitInOneSecond() {
isExit = true;
HandlerThread thread = new HandlerThread("doTask");
thread.start();
new Handler(thread.getLooper()).postDelayed(task, 1000);
} public boolean isExit() {
return isExit;
} public void setExit(boolean isExit) {
this.isExit = isExit;
}
Android_按两次返回键退出程序和长按返回键退出程序

长按返回键退出程序:

Android_按两次返回键退出程序和长按返回键退出程序
public boolean dispatchKeyEvent(KeyEvent event)
{
int keyCode=event.getKeyCode();
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK: {
if(event.isLongPress())
{
this.stopService(intent);
System.exit(0);
return true;
}else
{
return false; }
}
}
return super.dispatchKeyEvent(event); }
Android_按两次返回键退出程序和长按返回键退出程序

方法二:

Android_按两次返回键退出程序和长按返回键退出程序
private long exitTime = 0; 

@Override 

public boolean onKeyDown(int keyCode, KeyEvent event) { 

if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){ 

if((System.currentTimeMillis()-exitTime) > 2000){ 

Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show(); 

exitTime = System.currentTimeMillis(); 

} else { 

finish(); 

System.exit(0); 

} 

return true; 

} 

return super.onKeyDown(keyCode, event); 

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