What is the difference between Android timer and a Handler to do action every N seconds?

Technology CommunityCategory: AndroidWhat is the difference between Android timer and a Handler to do action every N seconds?
VietMX Staff asked 3 years ago

android.os.Handler is part of Android framework, the job will execute on the UI or main thread if you have created the Handler in the UI or main thread. Note that in Android you can only update views from the UI thread.

java.util.Timeron the other hand will execute on another thread so it cannot update the views.

So Handler is the recommended here. If you really want to use Timer you have to use runOnUiThread like:

new Timer().schedule(new TimerTask() {
    @Override
    public void run() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //this will run on UI thread so you can update views here
            }
        });
    }
}, 2000, 2000);