MediaPlayer, ProgressBar

前端 未结 3 638
心在旅途
心在旅途 2020-12-03 08:18

Is this the correct way to update a ProgressBar when playing Media? I figured there would be a callback in MediaPlayer, but I couldn\'t find it.

mediaPla         


        
3条回答
  •  鱼传尺愫
    2020-12-03 09:21

    The most efficient way is to use JRaymond's answer and EventBus

    private class MediaObserver implements Runnable {
        private AtomicBoolean stop = new AtomicBoolean(false);
        public void stop() {
            stop.set(true);
        }
    
        @Override public void run() {
            while (!stop.get()) {
                try {
                  if (player.isPlaying())
                     sendMsgToUI(player.getCurrentPosition(),
                                 player.getDuration());
                } catch (Exception e){e.printStackTrace();}
                try { 
                  Thread.sleep(100);
                } catch (InterruptedException e) { e.printStackTrace(); }
            }
        }
    }
    
    private MediaObserver observer = null;
    
    public void runMedia() {
        observer = new MediaObserver();
        new Thread(observer).start();
    }
    
    //handles all the background threads things for you
    private void sendMsgToUI(int position) {
        ChangingEvent event = new ChangingEvent(position);
        EventBus.getDefault().post(event);
    }
    

    ChangingEvent class would look something like that:

    public class ChangingEvent {
      private int position;
    
      public ChangingEvent(int position) {
          this.position= position;
      }
    
      public int getPosition() {
          return position;
      }
    }
    

    and in your Activity or Fragment all you have to do is

    class YouClass extends Activity {
      private EventBus eventBus = EventBus.getDefault();
    }
    
    @Override protected void onCreate(Bundle savedInstanceState) {
        //your code
        eventBus.register(this);
    }
    //eventbus that updates UI
    public void onEventMainThread(ChangingEvent event) {
        //seekbar or any other ui element
        seekBar.setProgress(event.getPosition());
    }
    

提交回复
热议问题