2

我需要每 10 秒从 Android 的服务器发送和获取一些东西。在这里,在 StackOverflow 和文档中,我发现了几十种实现它的方法(我尝试过的所有东西都可以完成这项工作),但似乎到处有人说这种方式有问题。

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

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

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

提前Tnx。

4

4 回答 4

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)
于 2012-08-28T12:19:29.987 回答
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);
于 2012-08-28T12:23:11.547 回答
1

执行重复任务很大程度上取决于任务的艰巨性/处理。UI 是否会阻止您的任务。如果是这样,那么您可以将 AsyncTask 与 Handler 和 TimerTask 结合使用。

在您的活动 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)
    }
于 2012-08-28T12:28:52.183 回答
0

我想我会使用这个Timer类:http TimerTask: //developer.android.com/reference/java/util/Timer.html

于 2012-08-28T12:17:25.157 回答