安排的AsyncTask为每分钟运行 [英] Schedule AsyncTask to run every minute

查看:138
本文介绍了安排的AsyncTask为每分钟运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是安排一个的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();
    }
  } 
}

这篇关于安排的AsyncTask为每分钟运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆