安排的AsyncTask为每分钟运行每分钟、AsyncTask

由网友(孤,不可无你)分享简介:什么是安排一个的AsyncTask 有它运行每分钟(注意的AsyncTask结束后我应该能够更新UI)的最佳实践。What is the best practice to schedule an AsyncTask to have it run every minute (note that after the As...

什么是安排一个的AsyncTask 有它运行每分钟(注意的AsyncTask结束后我应该能够更新UI)的最佳实践。

What is the best practice to schedule an AsyncTask to have it run every minute (note that after the AsyncTask has finished I should be able to update the UI).

我不打算对使用服务因为当应用程序被激活这些任务应该只运行。

I'm not intending on using a Service because these tasks should only run when app is active.

编辑:什么AsyncTask的只是下载从一个网络服务器JSON数据(我需要更新UI)。 JSON数据是pretty小需要几千字节。

What the AsyncTask is just downloading JSON data from a webserver (which I need to update UI). The JSON data is pretty small a couple of kilobytes.

推荐答案

我会使用一个定时对象。

有一个完整的例子:

public class TimerActivity extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    MyTimerTask myTask = new MyTimerTask();
    Timer myTimer = new Timer();

    myTimer.schedule(myTask, 3000, 1500);
  }

  // In this class you'd define an instance of your `AsyncTask` 
  class MyTimerTask extends TimerTask {
    MyAsyncTask atask;

    final class MyAsyncTask extends AsyncTask<Param1, Param2, Param3> {
      // Define here your onPreExecute(), doInBackground(), onPostExecute() methods
      // and whetever you need
      ...
    }

    public void run() {
      atask = new MyAsyncTask<Param1, Param2, Param3>();
      atask.execute();
    }
  } 
}
阅读全文

相关推荐

最新文章