gpt4 book ai didi

java - Android在IntentService中重复运行函数

转载 作者:行者123 更新时间:2023-12-02 00:26:53 25 4
gpt4 key购买 nike

我有这个 IntentService 代码,它运行一次服务:

protected void onHandleIntent(Intent intent) {
final ResultReceiver receiver = intent.getParcelableExtra("receiver");
String command = intent.getStringExtra("command");
Bundle b = new Bundle();
b.putString("results", results);
if(command.equals("query")) {
receiver.send(1, Bundle.EMPTY);
try {
results = sendGetMessage();
b.putString("results", results);
receiver.send(2, b);
} catch(Exception e) {
b.putString(Intent.EXTRA_TEXT, e.toString());
receiver.send(0, b);
}
}
this.stopSelf();
Log.d("ServiceFinished", "ServerConnection.java Service has finished");
}

我希望我的 sendGetMessage() 函数每 5 秒重复运行一次,直到我停止服务。我该怎么做?

最佳答案

您可能希望将其放入自己的线程中并永远循环。

Thread thread = new Thread()
{
@Override
public void run() {
try {
while(true) {
Thread.sleep(5000); // for the 5 seconds requirement
results = sendGetMessage();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};

thread.start();

关于java - Android在IntentService中重复运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9814376/

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