gpt4 book ai didi

Android:无法使用 Android 服务重复执行任务

转载 作者:搜寻专家 更新时间:2023-11-01 09:38:15 26 4
gpt4 key购买 nike

我在 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

}
}
}

如何使用服务重复执行某项任务?

最佳答案

好吧,您只向 Handler 发送一条消息。因此该消息将被处理一次。您可以让 Handler 再次传回相同的消息,但没有延迟这不是一个好主意——您会死锁主线程。重复做某事的最佳方式是分离出一个 Thread 并在 Thread 中执行它,并且 Thread 的 Runnable 永远循环。

关于Android:无法使用 Android 服务重复执行任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41498909/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com