2
我試圖每秒更新一次TextView。具體來說,這是一首歌曲的計時器。我正在使用Handler來實現這一點。它似乎設置正確 - 我沒有得到任何異常,我沒有看到任何明顯錯誤,當我調試 - 但它悄然無法更新TextView。它只停留在0:00。無法每秒更新TextView使用Handler
private TextView currentTime;
private int startTime = 0;
private Handler timeHandler = new Handler();
private Runnable updateTime = new Runnable() {
public void run() {
final int start = startTime;
int millis = appService.getSongPosition() - start;
int seconds = (int) ((millis/1000) % 60);
int minutes = (int) ((millis/1000)/60);
Log.d("seconds",Integer.toString(seconds)); // looks okay, prints new value every second
if (seconds < 10) {
// this is hit, yet the textview is never updated
currentTime.setText(String.format("%d:0%d",minutes,seconds));
} else {
currentTime.setText(String.format("%d:%d",minutes,seconds));
}
timeHandler.postAtTime(this,start+(((minutes*60)+seconds+1)*1000));
}
};
private ServiceConnection onService = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder rawBinder) {
appService = ((MPService.LocalBinder)rawBinder).getService(); // service that handles the MediaPlayer
// start playing the song, etc...
if (startTime == 0) {
startTime = appService.getSongPosition();
timeHandler.removeCallbacks(updateTime);
timeHandler.postDelayed(updateTime,1000);
}
}
public void onServiceDisconnected(ComponentName classname) {
appService = null;
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.song);
currentTime = (TextView) findViewById(R.id.current_time);
// ...
bindIntent = new Intent(Song.this,MPService.class);
bindService(bindIntent,onService,0);
}
任何想法?