user3422952
user3422952

Reputation: 317

Android - how to prevent UI lag via Handler?

I've got a Handler that runs a runnable task every 2 seconds. It runs a fairly intensive task (executes a shell command). Every time the I run handler.postDelayed(update, 2000); the user interface lags (for 2 seconds). How do I stop this lag?

I know there's lag because I have a dynamic interface, so I can move around a view and when the handler is run the interface becomes unresponsive for the 2 seconds.

Is there a way to go around this?

Upvotes: 0

Views: 3261

Answers (4)

user3422952
user3422952

Reputation: 317

I've fixed it. Thanks to everyone notifying me that the Handler runs on the UI thread... I've now run a separate thread to update the variable used in the handler task:

double p = 0;
public void z(){
    Thread t = new Thread(){
        @Override
        public void run(){
            p = a.b();
        }
    };
    t.start();
}
Runnable y = new Runnable() { 
    @Override 
    public void run() {
        z();
        c.setText(String.valueOf(p));
        d.setProgress(Float.valueOf(String.valueOf(p / 100)));
        handler.postDelayed(this, 2000);
    }
};`

Upvotes: 0

mattgmg1990
mattgmg1990

Reputation: 5876

You are doing this work on the main UI thread, which is not acceptable for your user to have a good experience, as you have already identified.

You can instead create a new background thread for your handler to run any posted runnables on, which will take the least amount of code change:

mHandlerThread = new HandlerThread("YourHandlerThread");
mHandlerThread.start();
handler = new Handler(mHandlerThread.getLooper());

// Now post your runnable, as before
handler.postDelayed(update, 2000);

Just keep in mind that you cannot touch any UI elements from this thread, as that is not allowed by Android.

Upvotes: 1

David Xu
David Xu

Reputation: 5597

Handler is a way to run code on the UI Thread in Android.

If you don't need your code run on the UI Thread, you may want to consider just making your own Thread or using an Executor.

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006614

when the handler is run the interface becomes unresponsive for the 2 seconds

That means that you are doing two seconds' worth of work on the main application thread. Doing 2 milliseconds' worth of work is more appropriate.

The Runnable that is passed to postDelayed() has its run() method called on the main application thread. If this work will take more than a millisecond or two, you should be using something other than Handler and postDelayed() for your every-two-seconds work, such as a ScheduledExecutorService.

Upvotes: 0

Related Questions