兩次點選BACK鍵退出應用的效果

螢草發表於2016-09-21

首先是監聽返回鍵的方法,有兩種:

  1. 在Activity中可以重寫如下方法
    public void onBackPressed() {
            Log.i(TAG,"返回鍵被點選了。");
            //需要遮蔽返回鍵註釋此行程式碼即可
            super.onBackPressed();//此方法自動呼叫finish()
        }

  2. @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            Log.i(TAG,"返回鍵被點選了。");
            //需要遮蔽返回鍵返回false即可
            //return false;
            return super.onKeyDown(keyCode, event);
        }

實現:

public class MainActivity extends AppCompatActivity {
    public static String TAG = "MainActivity";
    private boolean goBack = false;
    private boolean hasTask = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            hasTask = true;
            goBack = true;
        }
    };

    @Override
    public void onBackPressed() {
        Log.i(TAG, "返回鍵被點選了。");
        if (goBack) {
            goBack = true;
            Toast.makeText(getApplicationContext(), "再按一次返回鍵退出", Toast.LENGTH_SHORT).show();
            if (!hasTask) {
                timer.schedule(task, 3000);
            }
        } else {
            super.onBackPressed();
        }
    }
參考:

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);
}


相關文章