Android 取消返回键返回事件,返回桌面,再按一次退出程序,双击事件

mainactivity返回桌面代码:

activity下添加如下代码即可:

@Override
public void onBackPressed() {
    Intent home = new Intent(Intent.ACTION_MAIN);
    home.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    home.addCategory(Intent.CATEGORY_HOME);
    startActivity(home);

}

取消返回键返回事件:

activity下添加如下代码即可:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
             if (keyCode == KeyEvent.KEYCODE_BACK
                   && event.getAction() == KeyEvent.ACTION_DOWN) {
                     return true;
                }
           return super.onKeyDown(keyCode, event);
        }

 

再按一次退出程序

@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 {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);

        }
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

private long exitTime = 0;

 

双击事件:

 

    @Override//双击
   public boolean onTouchEvent(MotionEvent event) {
      switch (event.getAction()) {
         case MotionEvent.ACTION_DOWN:
            long current_time = System.currentTimeMillis();
            long d_time = current_time - last_time;
//                System.out.println(d_time);
            if (d_time < 300) {
               last_time = current_time;
               Log.i("lgq","双击了----"+last_time);
               return true;
            } else {
               last_time = current_time;
            }
            break;
      }
      return super.onTouchEvent(event);
   }

你可能感兴趣的:(移动开发)