我已经在android中编写了一个服务。我希望使用服务重复执行任务。这就是服务不应该死,应该重复执行任务。但是,该服务只执行一次任务然后被杀死。如何在后台重复执行任务。 我目前的代码是>
public class SyncService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
@Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(SyncService.this, "servicestarting", Toast.LENGTH_SHORT).show();
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}
@Override
public void onDestroy() {
Toast.makeText(SyncService.this, "service done", Toast.LENGTH_SHORT).show();
}
// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
Toast.makeText(SyncService.this, "repeatedly perform some task", Toast.LENGTH_SHORT).show();
//constantly perform task here
}
}
}
如何使用服务重复执行某项任务?
答案 0 :(得分:2)
您只需向处理程序发送一条消息。所以该消息将被处理一次。您可以让处理程序再次传回相同的消息,但没有任何延迟并不是一个好主意 - 您将使主线程死锁。反复执行某些操作的最佳方法是分离Thread并在Thread中执行,并使用Thread的Runnable永久循环。