user3709523 user3709523 - 1 month ago 5
Java Question

Android - how to run a piece of code every minute (synced with the device time)

I am developing an Android App in which I need to run a piece of code every minute, when I say every minute I mean it should be synced with the device's time so every time the device time changes by one minute my code is executed.

So far I tried this but it is not working:

runnable=new Runnable(){
@Override
public void run(){

long now=SystemClock.uptimeMillis();
long next=now+(60000 - now % 60000);
handler.postAtTime(this, next);

}
};
runnable.run();

Answer

You can use this code:

Thread thread = new Thread(new Runnable()
        {
            int lastMinute;
            int currentMinute;
            @Override
            public void run()
            {
                lastMinute = currentMinute;
                while (true)
                {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(System.currentTimeMillis());
                    currentMinute = calendar.get(Calendar.MINUTE);
                    if (currentMinute != lastMinute){
                        lastMinute = currentMinute;
                        Log.v("LOG", "your code here");
                    }
                }
            }
        });
        thread.run();
Comments