开发者

Unable to update TextView every second using Handler

I'm trying to update a TextView once per second. Specifically it's a timer for a song. I'm using a Handler to implement this. It seems to be set up correctly - I don't get any exceptions, and I don't see anything obviously wrong when I debug - but it quietly fails to update the TextView. It just stays at 0:00.

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 {
            current开发者_开发技巧Time.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);
}

Any ideas?


Solved it: Updating UI with Runnable & postDelayed not working with timer app

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜