gpt4 book ai didi

android - 为什么 runOnUiThread() 在服务内部不起作用?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:40:47 26 4
gpt4 key购买 nike

我正在创建一个需要每分钟更新值的应用程序,即使该应用程序未运行也是如此。

当然,我已经设置了一个简单的 Service 来执行此操作。我设置了调试消息来告诉我 Service 何时启动、何时更新(每分钟)以及何时关闭。当值在 runOnUiThread() 方法中更新时,我还会收到一条消息。除了 runOnUiThread() 中的消息外,我的所有消息都已激活。我做错了什么(当然有)?我需要更改什么?

代码:

@Override
public void handleMessage(Message message) {

try {

if (!serviceStarted) {

serviceStarted = true;
serviceTest = true;

while (serviceStarted) {

new MainActivity().runOnUiThread(new Runnable() {

public void run() {

OverviewFragment.refresh(getApplicationContext());
System.out.println("yay");

}
});

Thread.sleep(((1 /* minutes */) * 60 * 1000));
System.out.println("Updated values through service.");

}
}


} catch (InterruptedException e) {

Thread.currentThread().interrupt();
e.printStackTrace();

}

stopSelf(message.arg1);
}

最佳答案

So there's no need to do that, unless you're creating a Thread inside of it

Gabe Sechan 的回答是正确的。

但是,如果您使用的是单独的线程,则不要使用以下代码:

new MainActivity().runOnUiThread(new Runnable() {
public void run() {
OverviewFragment.refresh(getApplicationContext());
System.out.println("yay");

}
});

试试这个代码:

new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
OverviewFragment.refresh(getApplicationContext());
System.out.println("yay");
}
});

根据 Android docs

Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise).

关于android - 为什么 runOnUiThread() 在服务内部不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35930227/

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