Reputation: 1962
In order to execute some IO operations in my app I wrote a thread, there's nothing on its run method but it has several other methods, like void write(String filename, String data) and void create(String filename), all of which work like a charm. My question is, I used to think this thread was running on the background or something like this but since after removing the .run() statement on my main activity calling said methods still works, how can I have a thread running and waiting for a message from the activity without blocking the app? And second question, since the methods are still working does it mean they are being executed on the main UI thread when I call them from my main activity?
Upvotes: 2
Views: 2662
Reputation: 24820
For the methods to run on the said thread you will have to have to call your methods from the thread and not from any other thread.
class WorkerThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
Then use WorkerThread.mHandler.postRunnable
or sendMesssage
for the work to be done on another thread.
Upvotes: 2
Reputation: 68177
In order to make a que for processing stuff when delivered, you need to make use of android's native stuff which is the best option available:
For examples, read this and this.
Upvotes: 1
Reputation: 8030
You should use the start()
method, instead of the run()
.
With run()
you are running the given Runnable
in the calling thread.
With start()
you are starting a new thread that handles this Runnable
Upvotes: 3