简体   繁体   中英

mediaplayer and service class

i have a service class that run my mediaplayer it works fine, my only problem is that when my service create the mediaplayer it somewhat pause my UI like its hangs or something until my mediaplayer is done creating it self. what i want to happened is that when I press playbutton a toast message appears and display "Connecting" and when the mediaplayer is prepared displays a toast message says "Connected" then mediaplayer starts to play the music somehow my toast are not displaying and if they do its late..

heres my service code:

public class myservice extends Service {

MediaPlayer player;
private Handler UIHandler = new Handler();
private Uri source = Uri.parse("http://www.mydomain.com:8000/listen.mp3");

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

public void onCreate() {
    Toast.makeText(this, "Connecting", Toast.LENGTH_SHORT).show();
            player = MediaPlayer.create(this, source);
}

private void testtoast() {
    Toast.makeText(this, "Connecting", Toast.LENGTH_SHORT).show();
}

public void onStart(Intent intent, int StartId) {
    Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
    player.setOnPreparedListener( new OnPreparedListener() {
        public void onPrepared(MediaPlayer player) {
            // TODO Auto-generated method stub
            player.start();
        }
    });
}

public void onDestroy() {
    Toast.makeText(this, "Destroyed", Toast.LENGTH_SHORT).show();
    player.stop();
    player.release();
}
  }

Replace

      player = MediaPlayer.create(this, source);

with

      player = new MediaPlayer();
      player.setDataSource(source);
      player.prepareAsync();

MediaPlayer.create calls prepare() method to prepare MediaPlayer which is a synchronous operation and hangs the UI so you will experience a delay in your UI. So you should use .prepareAsync() explicitly to avoid this delay as provided in example above.

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