最有效的方法是使用JRaymond的回答和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類看起來類似的東西:
public class ChangingEvent {
private int position;
public ChangingEvent(int position) {
this.position= position;
}
public int getPosition() {
return position;
}
}
,並在您的活動或片段所有你需要做的就是
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());
}
謝謝,正是我所尋找的。 – pouzzler 2012-04-03 20:43:46
@pouzzler - 不客氣!查看MediaController類非常適合您提供有關製作自定義控制器的想法。 – 2012-04-03 21:16:14
由於數字千年版權法案刪除,第二個鏈接不見了:https://github.com/OESF/OHA-Android-4.0.1_r1.0 – astromme 2017-03-19 19:23:14