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

后端 未结 5 385
慢半拍i
慢半拍i 2020-12-03 03:33

I am having two activities A and B. when i click the button in A that will shows B. when i click the Button in B it backs to A. i had set the overridePendingTransition metho

相关标签:
5条回答
  • 2020-12-03 03:49
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            //Do stuff
        }
    
        return super.onKeyDown(keyCode, event);
    }
    
    0 讨论(0)
  • 2020-12-03 03:51

    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
    }
    
    0 讨论(0)
  • 2020-12-03 03:54
    @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

    0 讨论(0)
  • 2020-12-03 04:06

    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
    }
    
    0 讨论(0)
  • 2020-12-03 04:07

    More info on back key stuff can be found here: http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html

    0 讨论(0)
提交回复
热议问题