我在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
}
}
}
如何使用服务重复执行某些任务?
最佳答案
好吧,您只向处理程序发送一条消息。因此该消息将被处理一次。您可以让处理程序再次传递相同的消息,但没有延迟这不是一个好主意 - 您将使主线程死锁。重复执行某些操作的最佳方法是分离一个线程并在该线程中执行该操作,并且该线程的 Runnable 永远循环。
关于Android:无法使用android服务重复执行任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41498909/