I used postDelayed for delaying dynamic duration. And I found it did not work correctly. Here is my source code.
public Runnable service = new Runnable() {
public void run() {
endTimeHere = System.currentTimeMillis();
Log.d("Time",(endTimeHere-startTimeHere)/1000);
switch (step)
{
case 0:
delay = 0;
step = 1;
break;
case 1:
delay = 600; //delay 10 min = 600 sec
step = 2;
break;
case 2:
delay = 1200; //delay 20 min = 1200 sec
step = 3;
break;
case 3:
delay = 1800; //delay 30 min = 1800 secs
step = 0;
break;
default:
break;
}
startTimeHere = System.currentTimeMillis();
handler.postDelayed(service, delay*1000);
}
};
And I start and stop the handler in a BroadcastLintener.
public Handler handler = new Handler();
private BroadcastReceiver screenReceiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if(Intent.ACTION_SCREEN_ON.equals(action))
{
handler.removeCallbacks(service);
}
else if(Intent.ACTION_SCREEN_OFF.equals(action))
{
handler.post(service);
}
}
}
I'm sure that postDelayed is added in queue because the return value is true. However, the time duration I recorded is not matching with the delay value I set. For example, I set delay = 600 secs and the recorded duration = 958 secs.
Does anyone know why this happened?