停止声音服务

时间:2018-09-08 08:52:51

标签: android audio service background audio-player android-music-player

我正在使用BackGroundSound服务音乐,但是当我按下主页按钮或电源按钮或退出应用程序时,音乐并没有停止,我需要停止播放,任何人都有如何修复它的建议/想法。 ?我使用了本指南https://www.simplifiedcoding.net/android-service-example/

public class Backgroundsoundservice extends Service {
    private static final String TAG = null;
    MediaPlayer player;

    public IBinder onBind(Intent arg0) {

        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        player = MediaPlayer.create(this, R.raw.backgroundmusic01);
        player.setLooping(true); // Set looping
        player.setVolume(100,100);

    }
    @SuppressLint("WrongConstant")
    public int onStartCommand(Intent intent, int flags, int startId) {
        player.start();
        return 1;
    }

    public void onStart(Intent intent, int startId) {
        // TO DO
    }
    public IBinder onUnBind(Intent arg0) {
        // TO DO Auto-generated method
        return null;
    }

    public void onStop() {
        player.stop();

    }
    public void onPause()
    {
        player.pause();

    }
    @Override
    public void onDestroy() {
        player.stop();
        player.release();
    }

    @Override
    public void onLowMemory() {

    }
}

1 个答案:

答案 0 :(得分:0)

尝试像这样覆盖onPause。

@Override
protected void onPause() {
    super.onPause();
    if (mediaPlayer != null){
        mediaPlayser.stop();
        if (isFinishing()){
        mediaPlayer.stop();
        mediaPlayer.release();
        }
    }
}