MediaPlay in Android MusicServices crashes when ca

2019-08-28 19:12发布

问题:

In our app we have a MusicService. Currently, it works perfectly fine in terms of playing music and stopping it, but that is from starting and stopping the service. We are calling it in other methods, but mp.pause() is crashing unless it is surrounded by a null checker. But when it checks for nulls it doesn't work at all. We had all this working earlier, but we started reformatting the way were doing it, because on Android 4.0 (ICS) the Music kept playing randomly even when we stopped it, but thats not the point anyway.

public class MusicService extends Service {
    public static MediaPlayer mp;

    @Override
    public IBinder onBind(final Intent arg0) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mp = MediaPlayer.create(this, R.raw.title_music);
        mp.setLooping(true);
        mp.setVolume(200, 200);
    }

    @Override
    public int onStartCommand(final Intent intent, final int flags, final int startId) {
        mp.start();
        return 1;
    }

    @Override
    public void onStart(final Intent intent, final int startId) {

    }

    public IBinder onUnBind(final Intent arg0) {
        return null;
    }

    public static void onStop() {
        mp.stop();
        mp.release();
    }

    public static void onPause() {
        if (mp!=null) {
            mp.pause();
        }
    }

    public static void onResume() {
        if (mp!=null) {
            mp.start();
        }
    }


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

    @Override
    public void onLowMemory() {
        mp.stop();
        mp.release();
    }

}

We are using this to start the service in another activity:

intent = new Intent(this, MusicService.class);
    startService(intent);

回答1:

Without a log I can't really say with 100% certainty this is the issue, but it would appear that the pause method is being called while mp is in an invalid state. I suggest you change your onPause method so that it reads like so.

public static void onPause() {
    if (mp!=null) {
        if (mp.isPlaying())
            mp.pause();
    }
}

This will check to see if it is actually playing and will work for any state it is in, except an error state. At least according to the documentation.