3

我最近对此感到非常困惑,无法在任何地方找到答案。

在为 android 编程时,我想每 10 秒更新一次 textview,但我该怎么做呢?我已经看到一些示例使用“Run()”和“Update()”,但是当我尝试它时这似乎没有帮助,有什么想法吗?

现在我有:

public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.slideshow); CONST_TIME = (int) System.currentTimeMillis(); Resources res = getResources(); myString = res.getStringArray(R.array.myArray); } public void checkTime(View V){ TextView text = (TextView) findViewById(R.id.fadequote); CUR_TIME = (int) System.currentTimeMillis(); text.setText(""+(int) (CUR_TIME-CONST_TIME));//Debugs how much time has gone by if(CUR_TIME-CONST_TIME>10000){ getNextQuote(null); //A function that gets a random quote CONST_TIME = CUR_TIME; } }

我想我真正要问的是如何让 checkTime() 无休止地重复它,直到 onPause() 被调用?

4

5 回答 5

15

而不是在后台线程上大惊小怪,然后runOnUiThread()使用postDelayed(), available on anyView来安排一个Runnable. 这Runnable可以更新您的TextView信息,然后自行安排下一次通行证。使用后台线程来观看时间滴答是一种浪费。

于 2011-01-23T23:29:26.360 回答
10

使用计时器怎么样?

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

通过 timer.cancel() 取消它。在您的 run() 方法中,您可以使用 runOnUiThread();

更新:

我有一个 livescoring 应用程序,它使用这个 Timer 每 30 秒更新一次。它看起来像这样:

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");
    }
}
于 2011-01-23T21:15:43.260 回答
8

我同意 Wired00 的回答,但请遵循以下顺序:

        //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);
于 2014-11-07T03:54:07.163 回答
5

以防它帮助某人这里是一个示例代码使用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);


    }
};
于 2012-08-14T03:38:36.703 回答
0

使用线程。请参阅无痛穿线

于 2011-01-23T21:13:25.303 回答