Override back button in android

前端 未结 2 1009
Happy的楠姐
Happy的楠姐 2020-12-06 19:27

I have to play a mp3 file and when click on back button on the device then automatically the song should stop. So I tried below given method. But it is not working.

相关标签:
2条回答
  • 2020-12-06 19:38

    for Handleing All key use

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) { //Back key pressed
           //Things to Do
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    0 讨论(0)
  • 2020-12-06 19:46

    I don't know if this is your problem, but when you call onBackPressed(); in your onkeydown, you are not returning, so the parent.onkeydown is also called, and the 'normal' back is just being 'executed'.

    Insert a return statement there so you will not do the normal function from the parent class.

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (Integer.parseInt(android.os.Build.VERSION.SDK) < 5
                && keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            Log.d("CDA", "onKeyDown Called");
    
            onBackPressed();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    0 讨论(0)
提交回复
热议问题