实施定期行动的适当方式

时间:2012-08-28 12:15:01

标签: java android service scheduled-tasks task

我需要每隔10秒从Android服务器发送一些内容。在这里,在StackOverflow上,在文档中,我发现了几十种实现它的方法(我尝试过的所有工作都可以完成这项工作),但似乎每个人都会用这种方式说错了。

我尝试使用循环AsyncTask直到它被取消(直到活动被杀死),我发现它不是一个好的解决方案。在此之前我尝试了常规Threads,然后我发现它耗尽了很多电池。

现在我使用Runnable和ScheduledExecutorService的scheduleAtFixedRate函数完成了它,类似于此处提出的代码: How to run an async task for every x mins in android?。不用说,它有效。但是如果我的Activity在后台,例如用户正在接听来电,它会工作吗?

最后,我不知道在Android手机上最合适的方式是什么。

提前Tnx。

4 个答案:

答案 0 :(得分:1)

使用Handler它有各种方法,如postDelayed(Runnable r, long delayMillis),postAtTime(Runnable r, Object token, long uptimeMillis)等。

Handler mHandler =  new Handler() {
    public void handleMessage(Message msg) {

      //Start runnable here.
    }
   };

mHandler.sendMessageDelayed(msg, delayMillis)

答案 1 :(得分:1)

如果您的计划任务当前未运行,则建议您使用AlarmManagerBroadcastReceivers

否则文档建议使用Handlers

正如AmitD的问题评论所述。如果任务需要在后台运行,则可以在处理程序回调中使用AsyncTask来实现此目的。

final Handler handler = new Handler() {
  public void handlerMessage(Message msg) {
    new AsyncTask<TaskParameterType,Integer,TaskResultType>() {
      protected TaskResultType doInBackground(TaskParameterType... taskParameters) {
        // Perform background task - runs asynchronously
      }
      protected void onProgressUpdate(Integer... progress) {
        // update the UI with progress (in response to call to publishProgress())
        // - runs on UI thread
      }
      protected void onPostExecute(TaskResultType result) {
        // update the UI with completion - runs on UI thread
      }
    }.execute(taskParameterObject);
  }
};
handler.postMessageDelayed(msg, delayMillis);

对于重复执行,该文档还提到ScheduledThreadPoolExecutor作为选项(优先于java.util.Timer,主要是因为它具有额外的灵活性)。

final Handler handler = new Handler() {
  public void handlerMessage(Message msg) {
    // update the UI - runs on the UI thread
  }
};
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
ScheduledFuture f = exec.scheduleWithFixedDelay(new Runnable() {
    public void run() {
      // perform background task - runs on a background thread
      handler.sendMessage(msg); // trigger UI update
    }
  }, 0, 10, TimeUnit.SECONDS);

答案 2 :(得分:1)

实施重复任务很大程度上取决于任务的庞大/处理。 UI会阻止您的任务。如果是这样,那么你可以使用Handler和TimerTask进行AsyncTask。

在您的活动onCreate或任何通用功能中:

final Handler handler = new Handler();
    timer = new Timer();
        doAsynchronousTask = new TimerTask() {
           @Override
           public void run() {
            // TODO Auto-generated method stub
            handler.post(new Runnable() {
                 public void run() {
                try {
                 // Instantiate the AsyncTask here and call the execute method

                } catch (Exception e) {
                    e.printStackTrace();
                }

          }
        });
    timer.schedule(doAsynchronousTask,0,UPDATE_FREQUENCY)
    }

答案 3 :(得分:0)

我想我会将Timer课程与TimerTaskhttp://developer.android.com/reference/java/util/Timer.html

一起使用
相关问题