Updating TextView every N seconds?

扶醉桌前 提交于 2019-11-27 14:53:53

What about using a timer?

private Timer timer = new Timer();
private TimerTask timerTask;
timerTask = new TimerTask() {
 @Override
 public void run() {
    //refresh your textview
 }
};
timer.schedule(timerTask, 0, 10000);

Cancel it via timer.cancel(). In your run() method you could use runOnUiThread();

UPDATE:

I have a livescoring app, which uses this Timer to update it every 30 sec. It looks like this:

private Timer timer;
private TimerTask timerTask;

public void onPause(){
    super.onPause();
    timer.cancel();
}

public void onResume(){
    super.onResume();
    try {
       timer = new Timer();
       timerTask = new TimerTask() {
          @Override
          public void run() {
         //Download file here and refresh
          }
       };
    timer.schedule(timerTask, 30000, 30000);
    } catch (IllegalStateException e){
       android.util.Log.i("Damn", "resume error");
    }
}

Rather than fuss with a background thread and then runOnUiThread(), use postDelayed(), available on any View, to schedule a Runnable. That Runnable can update your TextView and then schedule itself for the next pass. Using a background thread for the purposes of watching time tick by is a waste.

Dhwaneel

I agree with Wired00's answer but please follow this order:

        //update current time view after every 1 seconds
        final Handler handler=new Handler();

        final Runnable updateTask=new Runnable() {
            @Override
            public void run() {
                updateCurrentTime();
                handler.postDelayed(this,1000);
            }
        };

        handler.postDelayed(updateTask,1000);

incase it helps someone here is an example code using postDelayed()

...

private Handler mHandler = new Handler();

...

// call updateTask after 10seconds
mHandler.postDelayed(updateTask, 10000);

...

private Runnable updateTask = new Runnable () {
    public void run() {
        Log.d(getString(R.string.app_name) + " ChatList.updateTask()",
                "updateTask run!");

                    // run any code here...         

                    // queue the task to run again in 15 seconds...
                    mHandler.postDelayed(updateTask, 15000);


    }
};

Use a thread. See Painless Threading.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!