背景音乐服务无法关闭



我有一项服务,它在我的应用程序的所有活动中都播放背景音乐。在我添加的每项活动中:

public void onPause() {
    super.onPause();
    stopService(new Intent(OpenerPlay.this, MusicDoctorService.class));
}
public void onStop() {
    super.onStop();
    stopService(new Intent(OpenerPlay.this, MusicDoctorService.class));
}
public void onResume() {
    super.onResume();
    startService(new Intent(OpenerPlay.this, MusicDoctorService.class));
}
public void onRestart() {
    super.onRestart();
    startService(new Intent(OpenerPlay.this, MusicDoctorService.class));
}

我的目的是停止或恢复服务,当我关闭应用程序或关闭屏幕时播放音乐。但是当我切换到另一个活动时,它也会停止。我应该更改服务代码中的内容吗?最后:我希望我的服务播放音乐以停止在屏幕上关闭或关闭应用程序关闭,但在活动切换期间不关闭。

服务:

public class MyService extends Service {

private 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.music);
    player.setLooping(true); // Set looping
    player.setVolume(100, 100);


}
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;
}

protected void onStop() {
    player.pause();
}
public void onPause() {
    player.pause();
}
@Override
public void onDestroy() {
    player.stop();
    player.release();
}
@Override
public void onLowMemory() {
}

}

在您的活动的ondestroy方法中尝试一下...

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(isMyServiceRunning(MyService.class))
        {
            stopService(new Intent(this, MyService.class));
        }
    }

private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

在这里活动完成后,您应该停止服务。

在您的服务中,您也应该发布mediaplayer

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

最新更新