I have a Runnable r
that is triggered periodically once per minute by handler.postDelayed(60*1000)
. And I test my code on a real device.
However I notice, when the phone is charging (AC or USB) , it works well, but if the phone is disconnected, the Runnable r
will only run once every 20min or even worse, several hours. Thanks for any help!
Below is the code:
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();
}
};
In the Handler:
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
...
...
}
}
}