简体   繁体   中英

Android: What happens to MediaPlayer after Service START_STICKY?

Take a look at this excert from a service class I have to stream online radios:

public class StreamingService extends Service implements MediaPlayer.OnPreparedListener {

private static final String TAG = StreamingService.class.getSimpleName();
public static final String EXTRA_STATION_IP = "STATION_IP";
private MediaPlayer player = null;

@Override
public void onCreate() {
    super.onCreate();
    Log.d(TAG, "Service Initialization.");

    // initialize player
    player = new MediaPlayer();
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    player.setOnPreparedListener(this);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "Service is Starting.");

    if(intent == null) {
        // service restarted
        player.prepareAsync();
    }

    return START_STICKY;
}

I know that returning START_STICKY will restart my service when possible and recall onStartCommand() with a null intent.. What I don't know is if my MediaPlayer instance will be in the same state after this restart.. For example, imagine I start streaming some online radio and after a few time the service got killed and restarted, am I able to just detect the null intent and run player.prepareAsync(); (just like I'm doing), or will I have to use setDataSource(); again to let the player know the url to stream?

If you get restarted its because the system has killed your service. You will get a new onCreate and new onStartCommand (you go through the entire life cycle again). So your audio instance will not be the same, but that shouldn't be a problem since you get to set it up again in onCreate .

If the location you stream from is set from outside your service you will need to store the location when you set it and set it again when you are re-created. If the location comes in the onStartCommand intent you can use the FLAG_REDELIVER_INTENT , in order to get your last intent redelivered to you. If you go this route, keep in mind that the system will not redeliver your intents indefinitely.

Remember to do any clean up necessary in onDestroy , which may or may not be called when your service gets killed by the system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM