is there a default back key(on device) listener in android?

被刻印的时光 ゝ 提交于 2019-11-27 13:13:49
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        // do something on back.
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

The following link is a detailed explanation on how to handle back key events, written by the Android developers themselves:

Using the back key

Nikolay Ivanov

For Android 2.0 and later, there is a specific method in the Activity class:

@Override  
public void onBackPressed() {
    super.onBackPressed();   
    // Do extra stuff here
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_BACK){
        //Do stuff
    }

    return super.onKeyDown(keyCode, event);
}

I use this code on an activity with a media player. I needed to stop the playback when user pressed the back button but still be able to go back to previous activity.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        // do something on back.
        try{
            mp.stop(); //this line stops the player
            return super.onKeyDown(keyCode, event);//this line does the rest 
        }
        catch(IllegalStateException e){
            e.printStackTrace();
        }
        return true;
    }

    return super.onKeyDown(keyCode, event); //handles other keys
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!