Reputation: 3409
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
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
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