背景音乐服务不会关闭

时间:2016-12-29 16:59:31

标签: android android-studio service media-player

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

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() {

}

}

1 个答案:

答案 0 :(得分:0)

在您的活动的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();
        }
    }
}
相关问题