user3141990
user3141990

Reputation: 139

How to send a Message from a seperate thread to the UI thread?

I am trying to find a way to send a message from the a seperate thread to the UI Thread, is that possible? The thread has not been launched from the MainActivity but from a service, does it make any difference.

Thanks in advance for you help.

Here is the thread from where i would like to send the message i receive to the UI Thread

   import java.io.BufferedReader;
   import java.io.IOException;

   import android.os.Bundle;
   import android.os.Handler;
   import android.os.Message;
   import android.util.Log;

    public class Receive_Client implements Runnable {
    private BufferedReader in;
    private String message=null;

    // The Bundle will hold the String "Location or message" and will transmit it to the     handler in the mainActivity
      private String[] messageArray=new String[3];
      Bundle messageBundle=new Bundle();
    // corresponds to the message that will be exchange it with the UIThread Handler

     private Message Message;

  public Receive_Client(BufferedReader in) {
  this.in=in;


     }
@Override
public void run() {
    // If isRunning is at false the Thread have to stop
    while(isRunning.get()){// error here---------->
        try{
            while (isPausing.get() && (isRunning.get())) {//here also -------->
                // Pausing the Thread to relax the CPU 

                Thread.sleep(2000);
            }
            if ((message=in.readLine())!=null){
                //message=in.readLine();
                Log.d(MainActivity.TAG, "the server say"+message);
                // Sending the message to the Handle (the method handler.obtainMessage is more efficient
                // rather than using a message from zero, optimizing the message pool to the handler)
                // message instanciation
                messageArray=message.split(",");
                Message=handler.obtainMessage();    //---------> the handler also
                // Adding data to transmit to handler via Bundle

                messageBundle.putStringArray(RECEIVE_LOCATION, messageArray);// the key is not recognized too----->
               //adding the bundle to the message
                Message.setData(messageBundle);
                //send the message
                handler.sendMessage(Message);


            }
            }catch (IOException e){
                Log.d(MainActivity.TAG, e.getMessage());}

            }


    }

    }

Upvotes: 2

Views: 2285

Answers (4)

Piotr Ślesarew
Piotr Ślesarew

Reputation: 2836

Try to use EventBus. For me is the best way to to communicate between Services, Fragments and Activities. You can also send messages from background thread to ui thread.

Upvotes: 0

Prachur
Prachur

Reputation: 1110

Look for worker thread in below link also post and postdelayed.

worker thread

Upvotes: 0

Andre Perkins
Andre Perkins

Reputation: 7800

What you want to use is a handler. You can use these objects to send messages in between different threads. A handler will receive messages for the thread that it was instantiated in. Therefore, create a handler for each thread and then implement the appropriate callbacks.

http://developer.android.com/reference/android/os/Handler.html

Upvotes: 0

doorstuck
doorstuck

Reputation: 2308

You will have some code like this anywhere you want: service, activity, etc. (this is a Context):

LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
Intent i = new Intent(REFRESH_CONSTANT);
lbm.sendBroadcast(i);

Then in your UI you listen for this broadcast:

public class MyFragment extends Fragment {

    MyReceiver r;

    public void refresh() {
        // Do the refresh
    }

    public void onPause() {
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(r);
    }

    public void onResume() {
        r = new MyReceiver ();
        LocalBroadcastManager.getInstance(mContext).registerReceiver(r,
            new IntentFilter(REFRESH_CONSTANT));
    }

    private class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            MyFragment.this.refresh();
        }
    }
}

You can put more data in the intent object as needed.

Upvotes: 1

Related Questions