2

我必须每隔一秒在后台运行一些代码,代码将调用一个搜索数据库并向应用程序返回值的 Web 服务。我的问题是哪种方法最有效?我已经阅读了 Timers、Threads、AsyncTask 和 Services,它们似乎各有利弊。考虑到执行时间和电池寿命,请有人告诉我哪个是最好的。

谢谢

更新: 我决定使用 Aysnc 任务在后台运行我的代码,同时使用 TimeTask 定期触发 AsyncTask。这样,当我离开该特定活动时,操作就会被破坏

4

4 回答 4

3

您应该使用该服务来执行后台操作,但在您的情况下,您希望在 1 秒内运行代码,这里是使用处理程序的服务示例,它每 1 秒调用一次。

public class YourService extends Service {
private static final String TAG = "Your Service";
private final Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {

}
};
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
//  Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate");

}

@Override
public void onDestroy() {
    super.onDestroy();
//  Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    handler.removeCallbacks(sendUpdatesToUI);   
}
 private Runnable sendUpdatesToUI = new Runnable() {
        public void run() {
            /// Any thing you want to do put the code here like web service procees it will run in ever 1 second
            handler.postDelayed(this, 1000); // 1 seconds
        }
 };
@Override
public void onStart(Intent intent, int startid) {

    handler.removeCallbacks(sendUpdatesToUI);
    handler.postDelayed(sendUpdatesToUI, 1000);//1 second       
    Log.d(TAG, "onStart");
}

}

并且每次android在3或4小时内空闲服务时服务都无法运行我建议您使用前台服务来长时间运行您的进程。

于 2012-06-11T09:01:09.263 回答
2

对于这样的操作,我倾向于使用服务组件。对于任务本身,我使用了一个 AsyncTask,它会在重复之前等待一段设定的时间(使用 while 循环)。

于 2012-06-11T08:55:09.310 回答
0

您必须创建一个新的Thread,以便在通话时间比预期更长的情况下通话不会锁定设备。这AsyncTask是一种使用多线程的简单方法,但它缺乏重复任务的功能。我会说您最好使用 aTimer或更新的ScheduledExecutorService. 如果你选择使用Timer你创建一个TimerTask你可以交给它。取而代之的ScheduledExecutorService是 Runnable。

您可能希望将线程包装在一个Service(服务不提供新线程)中,但这并不总是必要的,具体取决于您的需要。

正如评论中所建议的,您也可以使用Handler.postDelayed(). 虽然您仍然需要创建一个新线程然后调用Looper.prepare()它:

  class LooperThread extends Thread {
      public Handler mHandler;

      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }

(来自Looper 文档的代码)

还; 每秒调用 Web 服务似乎太频繁了,尤其是当用户连接速度较慢或有数据需要传输时,尽量减少调用。

于 2012-06-11T08:57:29.200 回答
0

我认为这不仅仅是一种解决方案,所以这取决于你。您可以尝试使用此运行方法启动线程:

private final int spleeptime = 1000;
public boolean running;

@Override
public void run() {
    while (running) {
        try {
            int waited = 0;
            while ((waited < spleeptime)) {
                sleep(100);
                waited += 100;
            }
        } catch (InterruptedException e) {
        } finally {
            // your code here
        }
    }
}
于 2012-06-11T08:58:01.417 回答