Search code examples
javaandroidmultithreadingrunnableandroid-looper

Android: How to create and pass messages to worker thread from main thread


I'm new to multithreading in android and java, I'm having difficult time implementing a simple model in which we can start worker thread and send some message or runnable to the worker thread from main thread where it does some operation and send result to main thread and updating ui thread

I tried this:

public class NewThreadUsingRunnable implements Runnable {

Handler handler;

@Override
public void run() {

    handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Log.i("Message Recieved", " " + msg);
            int result = 2+2
        }
    };
}

MainActivity:

new NewThreadUsingRunnable().run();

Solution

  • For those who wants Answer about this(because it has reached to popular question):

    First of all you need to create Looper thread and have handler initialize along with Looper

    Use Handler of worker/main thread and append message to it - In message object you can pass Constant, String and even bundle to and from worker thread