运行时异常“无法在未调用looper.prepare()的线程内创建处理程序”

时间:2022-04-07 20:44:33

I am making a UDP server which receives a string, I have to modify that string, but I can't seem to figure out how to forward the string to the class that is supposed to handle the string, I get the following exception:

我正在创建一个接收字符串的UDP服务器,我必须修改该字符串,但我似乎无法弄清楚如何将字符串转发到应该处理该字符串的类,我得到以下异常:

"can't create handler inside thread that has not called looper.prepare()"

“无法在未调用looper.prepare()的线程内创建处理程序”

I have little experience with android and can't figure out how to solve the problem, and none of the other questions about this seemed to give me the answer.

我对android几乎没有经验,也无法弄清楚如何解决这个问题,而其他任何关于这个的问题似乎都没有给我答案。

public class Server implements Runnable {

 @Override
 public void run() {
     while(!start)
     {
         //do nothing
     }
     try {
         InetAddress serverAddr = InetAddress.getByName(SERVERIP);
         //updateTrack("\nServer: Start connecting \n");
         DatagramSocket socket = new DatagramSocket(SERVERPORT, serverAddr);
         byte[] serverBuf = new byte[1064];
         DatagramPacket packet = new DatagramPacket(serverBuf, serverBuf.length);
         //updateTrack("Server: Receiving \n");
         socket.receive(packet);
         int realSize = packet.getLength();
         byte[] RealServerBuf = new byte[realSize];
         System.arraycopy (serverBuf, 0, RealServerBuf, 0, realSize);
         recived =  new String(RealServerBuf);
         //updateTrack("Server: " + recived + "\n");
         StringHandler stringHandler = new StringHandler();  
         stringHandler.StringSplitter(recived);
         updateTrack("Server: Succeed\n");
     } catch (Exception e) {
         updateTrack("Server: Error\n" + e);
     }
   }
}

Tthe problem has something to do with how I instantiate the StringHandler.class and it not being connected with the UI-thread, but I can't figure out how to do it.

该问题与我如何实例化StringHandler.class并且它没有与UI线程连接有关,但我无法弄清楚如何做到这一点。

2 个解决方案

#1


0  

Put your code inside runOnUiThread

将您的代码放在runOnUiThread中

activity.runOnUiThread(new Runnable() {
  public void run() {
    // your code here
  }
});

Please, look at this for further details.

请看这个以获取更多细节。

#2


0  

Put Your code inside

把你的代码放进去

activity.runOnUiThread(new Runnable() {
  public void run() {
   // your code here
 }
});

#1


0  

Put your code inside runOnUiThread

将您的代码放在runOnUiThread中

activity.runOnUiThread(new Runnable() {
  public void run() {
    // your code here
  }
});

Please, look at this for further details.

请看这个以获取更多细节。

#2


0  

Put Your code inside

把你的代码放进去

activity.runOnUiThread(new Runnable() {
  public void run() {
   // your code here
 }
});