Sver
Sver

Reputation: 3409

Confused with threading - Handler blocks UI thread

I have a time consuming task (iterating through files and sending it's content to server) that I want to execute in background thread, in specific interwal (that's why I want to use Handler).

From UI thread I have a call like this:

LogsManager lm;
lm = new LogsManager(this);
lm.processLogFiles();

And in LogsManager class I have following piece of code:

public void processLogFiles(){
    Handler mHandler = new Handler();
    mHandler.postDelayed(logsRunable, 1000);    
}

private Runnable logsRunable = new Runnable() {
        @Override
        public void run() {
            File f = new File(Environment.getExternalStorageDirectory()+Constants.LOG_DIR);             
            File[] logFiles = f.listFiles();
            for (int i = 0; i < logFiles.length; i++) {
                readLogs(logFiles[i]); // executes some other methods inside
            }
        }
    };

As you can see it's just method with Handler that calls Runnable. And, unfortunately it also blocks my UI thread. Isn't Handler supposed to start a new thread for Runnable? I use handlers in other parts of my app also, and they works just fine. Am I'm doing something wrong?

Upvotes: 1

Views: 5363

Answers (4)

David Guo
David Guo

Reputation: 1759

I also think AsyncTask is a good solution for your case.

Upvotes: 0

Nikolay Elenkov
Nikolay Elenkov

Reputation: 52966

All the post* methods in Handler run code on Handler's original thread (in your case the GUI thread). If you want a background thread, you need to explicitly start one (see below) or use AsyncTask, if you need to update the GUI.

Thread t = new Thread(logsRunable);
t.start();

Upvotes: 3

denis.solonenko
denis.solonenko

Reputation: 11775

As stated in the docs, Handler:

When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it

So if you're creating mHandler in UI thread, then it will run the tasks in UI thread - hence the problem.

Upvotes: 10

Rasel
Rasel

Reputation: 15477

I think you should use AsyncTask class for this purpose.

Scheduled the execution for the task after a specific delay, in your case it is 1000.

Upvotes: 0

Related Questions