如何从单独的线程向UI线程发送消息?

时间:2014-01-09 20:01:12

标签: android multithreading handler atomic ui-thread

我试图找到一种方法从单独的线程向UI线程发送消息,这可能吗? 该线程尚未从MainActivity启动,但是从服务启动,它是否有所不同。

先谢谢你的帮助。

这是我希望将收到的消息发送到UI线程的线程

   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());}

            }


    }

    }

4 个答案:

答案 0 :(得分:2)

您可以随时随地获得这样的代码:服务,活动等。(thisContext):

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

然后在你的用户界面中,你会收听这个广播:

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();
        }
    }
}

您可以根据需要在intent对象中添加更多数据。

答案 1 :(得分:0)

您想要使用的是处理程序。您可以使用这些对象在不同的​​线程之间发送消息。处理程序将接收它实例化的线程的消息。因此,为每个线程创建一个处理程序,然后实现适当的回调。

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

答案 2 :(得分:0)

查找以下链接中的工作线程也可以发布和后延迟。

worker thread

答案 3 :(得分:0)

尝试使用EventBus。对我来说,这是在服务,碎片和活动之间进行通信的最佳方式。您还可以将消息从后台线程发送到ui线程。

相关问题