gpt4 book ai didi

android - 为什么手机的充电状态会影响我的应用程序的行为

转载 作者:行者123 更新时间:2023-11-30 01:56:00 28 4
gpt4 key购买 nike

我有一个 Runnable r,它由 handler.postDelayed(60*1000) 每分钟定期触发一次。我在真实设备上测试我的代码。

但是我注意到,当手机充电时(AC 或 USB),它工作正常,但如果手机断开连接,Runnable r 将每 20 分钟或更糟,仅运行一次,几个小时。感谢您的帮助!

代码如下:

private final Runnable listen_to_server = new Runnable(){
public void run(){
new Thread() {
public void run() {
try {

handler.sendMessage(handler.obtainMessage(PING_SERVER,"listen"));
synchronized (listen) {
listen.wait();
}
handler.postDelayed(listen_to_server, 50000);
}
catch (Exception e) {
e.printStackTrace();
}

}
}.start();
}
};

在处理程序中:

    handler=new Handler() {
@Override
public void handleMessage(final Message msg) {
switch (msg.what) {
case PING_SERVER:
String type = (String) msg.obj;
add_log("ping server"); // print to screen and Log.d
...
...
}
}
}

最佳答案

引用this link我认为问题可能是,正如他们所说:

Android is not a real-time operating system. All postDelayed() guarantees is that it will be at least the number of milliseconds specified. Beyond that will be dependent primarily on what the main application thread is doing (if you are tying it up, it cannot process the Runnable), and secondarily on what else is going on the device (services run with background priority and therefore get less CPU time than does the foreground).

如何解决这个问题?在 this发布解决方案如下:

You'll probably have better luck using the AlarmManager for such a long delay. Handler is best for ticks and timeouts while your app is in the foreground.

所以尝试实现一个 AlarmManager 查看 the doc.

希望我有所帮助:)

关于android - 为什么手机的充电状态会影响我的应用程序的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32220504/

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