gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 00:24:08 25 4
gpt4 key购买 nike

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

}


}

}

最佳答案

你会在任何你想要的地方有这样的代码:服务、 Activity 等(this 是一个Context):

LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
Intent i = new Intent(REFRESH_CONSTANT);
lbm.sendBroadcast(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();
}
}
}

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

关于android - 如何将消息从单独的线程发送到 UI 线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21029974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com