2012-05-29 51 views
1

要更新一個seekbar,我使用下面的代碼: 我的問題是,seekBar.setProgress()調用時,UI上的其他元素會凍結,所以我想要一個不同的線程更新主線程中的seekBar。Android:線程更新UI

如何繼續?

private Handler mHandler = new Handler() { 
    @Override 
    public void handleMessage(Message msg) { 
     try { 
      int pos; 
      switch (msg.what) { 
      case SHOW_PROGRESS: 
       pos = setProgress(); 
       if (!mDragging && mBoundService.isPlaying()) { 
        msg = obtainMessage(SHOW_PROGRESS); 
        sendMessageDelayed(msg, 100 - (pos % 1000)); 
       } 
       break; 
      } 
     } catch (Exception e) { 

     } 
    } 
}; 

private int setProgress() { 
    if (mBoundService == null || mDragging) { 
     return 0; 
    } 
    int position = mBoundService.getCurrentPosition(); 
    int duration = mBoundService.getDuration(); 
    if (sliderSeekBar != null) { 
     if (duration > 0) { 
      // use long to avoid overflow 
      long pos = 1000L * position/duration; 
      sliderSeekBar.setProgress((int) pos); 
     } 
    } 

    if (sliderTimerStop != null) 
     sliderTimerStop.setText(stringForTime(duration)); 
    if (sliderTimerStart != null) 
     sliderTimerStart.setText(stringForTime(position)); 

    return position; 
} 
+0

http://samir-mangroliya.blogspot.in/p/android-asynctask-example.html –

+0

或者只是把它放在了Runnable,而且發表它。請參閱處理程序的後處理方法。 – nullpotent

+0

我不認爲調用seekBar.setProgress()只能凍結UI。而UI線程只存在一個。 – ATom

回答

4

活動有一個runOnUiThread方法,允許單獨的線程更新UI組件。你setProgress方法最終會看起來像:

private int setProgress() { 

    if (mBoundService == null || mDragging) { 
     return 0; 
    } 
    final int position = mBoundService.getCurrentPosition(); 
    final int duration = mBoundService.getDuration(); 

    runOnUiThread(new Runnable(){ 

     @Override 
     public void run(){ 

      if (sliderSeekBar != null) { 
       if (duration > 0) { 
        // use long to avoid overflow 
        long pos = 1000L * position/duration; 

        sliderSeekBar.setProgress((int) pos); 
       } 
      } 

      if (sliderTimerStop != null) 
       sliderTimerStop.setText(stringForTime(duration)); 
      if (sliderTimerStart != null) 
       sliderTimerStart.setText(stringForTime(position)); 
     } 
    }); 

    return position; 

}

+0

謝謝,解決了。 – Giuseppe