思路:
用定时器(timer)计时,当用户第一次点返回键时提示“再按一次退出”,两秒之内再点一次退出。不点就判断为误触。
package com.example.themtest; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } //重写onKeyDown方法,判断是否点击退出键 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub switch (keyCode) { case KeyEvent.KEYCODE_BACK: handleCilick();//点击就跳转到此方法 return true; default: break; } return super.onKeyDown(keyCode, event); } /* *此变量用来计算点的次数,初始值为false,第一点设置为true,如果第二次点就为false,退出 *如果没点就不做操作 */ private boolean isDoubleClick; Timer timer = new Timer(); private void handleCilick() { // TODO Auto-generated method stub System.out.println(isDoubleClick); if (!isDoubleClick) { isDoubleClick = true; //第二次点击,用到了TimerTask Toast.makeText(this, "再按一次推出", Toast.LENGTH_SHORT).show(); timer.schedule(new TimerTask() { @Override public void run() { // TODO Auto-generated method stub isDoubleClick = false; } }, 2000); } else { finish(); System.exit(0); } } }
时间: 2024-10-09 22:08:25