我正在创建一个接收字符串的UDP服务器,我必须修改该字符串,但我似乎无法弄清楚如何将字符串转发到应该处理该字符串的类,我得到以下例外:
"无法在未调用looper.prepare()"
的线程内创建处理程序我对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);
}
}
}
这个问题与我如何实例化StringHandler.class并且它没有与UI线程连接有关,但我无法弄清楚如何去做。
答案 0 :(得分:0)
将您的代码放在 runOnUiThread
中activity.runOnUiThread(new Runnable() {
public void run() {
// your code here
}
});
请查看this了解更多详情。
答案 1 :(得分:0)
将您的代码放入
activity.runOnUiThread(new Runnable() {
public void run() {
// your code here
}
});