Media Service Activity

痞子三分冷 提交于 2019-12-13 00:28:53

问题


I have an activity that is a service which plays audio using a media player. This is the service

class MusicService extends Service implements OnCompletionListener {
 MediaPlayer mediaPlayer;

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

 @Override
 public void onCreate() {
  mediaPlayer = MediaPlayer.create(this, R.raw.s);// raw/s.mp3
  mediaPlayer.setOnCompletionListener(this);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!mediaPlayer.isPlaying()) {
  mediaPlayer.start();
}
return START_STICKY;
 }

  public void onDestroy() {
   if (mediaPlayer.isPlaying()) {
  mediaPlayer.stop();
   }
   mediaPlayer.release();
 }

 public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
 }

}

Instead of playing from that raw file i want it to play from a path that is a String that comes from the sd card. the path is held in the class that calls the service how do i pass that string to the service class and put it in the mediaplayer create method. here is where i call the service

   private void playAudio(String url) throws Exception{
Intent music = new Intent(this,MusicService.class);
startService(music);

}


回答1:


Use the putExtra commands of the starting Intent:

music.putExtra(key, value);

Then get that passed info in the onStartCommand of your mediaplayer service:

intent.getExtras().getString(key);

Beware that this intent can be null in cases when the service is restarted by the system.



来源:https://stackoverflow.com/questions/8276381/media-service-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!