开发者

Android: Stop playback on Home or Back button

When 开发者_如何学编程I press back or home in my application, it hides, but the MediaPlayer keeps going. Is there a way to know when these buttons have been pressed and stop playback before closing?


just implement this method in your class where media player is calling...

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) 
        { //Back key pressed
           //Things to Do
            if(mediaPlayer!= null)
            {
                mediaPlayer.stop();
                mediaPlayer=null;
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


You should be able to override the onPause() function in your Activity. onPause() will be called when you Activity is hidden and you can pause the MediaPlayer there.

For example,

@Override
protected void onPause() {
    super.onPause(); // Don't forget this line
    myMediaPlayer.pause() // Or whatever the function is to pause it
}


Don't forget to add super.onPause; if you forget it will cause a FC.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜