我正在编写一个数据记录器应用程序,我需要每 5 分钟准确地发出一个 http 请求。用户知道电池耗尽,这对我来说没问题。我正在使用带有适当通知的前台服务,并且我有一个处理程序线程来女巫我每 5 分钟发布一次可运行的任务。似乎当手机进入打盹模式时,线程被挂起并且没有执行任何可运行的。这是正常行为还是我遗漏了什么?任何有关如何做到这一点的帮助将不胜感激。
启动线程的服务代码:
private void startTheForegroundService() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainService.this);
builder.setPriority(Notification.PRIORITY_HIGH);
startForeground(1000, builder.build());
httpThread = new HttpThread("Ping Thread", Thread.NORM_PRIORITY);
httpThread.start();
httpThread.loop();
}
线程代码:
public class HttpThread extends HandlerThread {
public Handler mHandler;
public HttpThread(String name, int priority) {
super(name, priority);
}
public synchronized void waitUntilReady() {
mHandler = new Handler(getLooper(), new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
return false;
}
});
}
public void loop() {
waitUntilReady();
mHandler.post(new Runnable(){
@Override
public void run() {
//code for the http request.
}
});
}
}