Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何将消息从单独的线程发送到UI线程?_Android_Multithreading_Handler_Atomic_Ui Thread - Fatal编程技术网

Android 如何将消息从单独的线程发送到UI线程?

Android 如何将消息从单独的线程发送到UI线程?,android,multithreading,handler,atomic,ui-thread,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.

我正在试图找到一种方法,将消息从一个单独的线程发送到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());}

            }


    }

    }

您可以在任何地方使用类似的代码:服务、活动等(
是一个
上下文
):

然后在UI中收听此广播:

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对象中放入更多数据。

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


在下面的链接中查找工作线程,也可以是post和POSTDELLATED


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

您可以将消息存储在SharedReferences中,然后从ui线程读取消息。如果是从服务,则您可能对使用本地广播感兴趣,但我正在运行的代码位于单独的线程中,我应该使用runOnUIThread()还是广播接收器。我有权在线程中拥有意图吗?发送广播不需要在UI线程上进行。它很少会。因此,不要使用runOnUIThread()。只需确保线程中有对上下文的引用(例如,将其传递到构造函数中并将其另存为字段)。如果工作线程是从另一个服务启动的,工作线程如何向处理程序发送消息?在第二个线程中创建的处理程序只需要引用在主线程中创建的处理程序。有多种方法可以做到这一点,最简单的方法是将主线程的处理程序引用传递给正在创建第二个线程的服务。我不确定是否正确理解您的答案。您能详细说明一下吗?您希望消息发送到的MainActivity中正在启动(或绑定到)的服务是什么?如果是这样,那么您可以通过一个函数将处理程序直接传递给服务,然后在创建第二个线程时,从服务中获取处理程序并对其进行调用。服务绑定到MainActivity I有同样的问题,如果工作线程是从另一个服务启动的,那么工作线程如何向UI线程处理程序发送消息?
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();
        }
    }
}