Tuesday, October 20, 2015

Android TimerTask on Background Service

For creating a timer task and running it periodically, say for e.g. making a network ping periodically can be achieved by the below code

class TimeDisplayTimerTask extends TimerTask {
    
    @Override
    public void run() {
        // run on another thread
        mHandler.post(new Runnable() {
            
            @Override
            public void run() {
                
                AppUtils.infoLog("--- Triggering Location Check ---");
                displayTimeInfo();
            }
            
        });
    }
}


if(mTimer != null) {
    mTimer.cancel();
}   // recreate new
mTimer = new Timer();
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);

Handler is mainly used to post data from background thread to UI thread. 

References:

No comments:

Post a Comment