Android的简单应用(二)——使用dispatchKeyEvent双击退出程序

Android系统按键操作最先是在dispatchKeyEvent中进行处理的,然后才是onKeyDown(int keyCode, KeyEvent event)和onKeyUp(int keyCode, KeyEvent event)。

同理,触摸操作也是先在dispatchTouchEvent中进行处理,在分发给onTouchEvent进行处理。

代码很简单,只要掌握好事件的分发顺序就ok了。
Activity中的代码:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        Log.d("CPACM","onKeyDown");
        return super.onKeyDown(keyCode, event);
    }

    
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        Log.d("CPACM","onKeyUp");
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        Log.d("CPACM","onTouchEvent");
        return super.onTouchEvent(event);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        Log.d("CPACM","dispatchKeyEvent");
        if(event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if(System.currentTimeMillis() - preTime < 2000){//在两秒内,退出
                
                return super.dispatchKeyEvent(event);
            }
Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
//System.exit(0);
preTime
= System.currentTimeMillis(); return true; } // TODO Auto-generated method stub return super.dispatchKeyEvent(event); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { // TODO Auto-generated method stub Log.d("CPACM","dispatchTouchEvent"); return super.dispatchTouchEvent(ev); }

 

顺便附一张截图~

Android的简单应用(二)——使用dispatchKeyEvent双击退出程序_第1张图片

 

 

你可能感兴趣的:(Dispatch)