Android $CalledFromWrongThreadException尝试获取字符串以发送到www.example.com时出现socket.io

iovurdzv  于 2022-12-09  发布在  Android
关注(0)|答案(1)|浏览(203)

我尝试从EditText获取字符串并使用www.example.com发出它socket.io,但是,每当运行此程序时,我总是收到错误android.view.ViewRootImpl$CalledFromWrongThreadException。
我尝试过:

System.out.println("current status : " + socket.connected());
EditText send_message = findViewById(R.id.send_message);
String message = send_message.getText().toString();
MainActivity.this.runOnUiThread(() -> socket.emit("send_message", send_message.getText().toString()));

发生的情况:

E/AndroidRuntime: FATAL EXCEPTION: EventThread
    Process: dev.atomtables.atomchat, PID: 3719
    android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
        at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6357)
        at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:874)
        at android.view.View.requestLayout(View.java:17476)
        at android.view.View.requestLayout(View.java:17476)
        at android.view.View.requestLayout(View.java:17476)
        at android.view.View.requestLayout(View.java:17476)
        at android.view.View.requestLayout(View.java:17476)
        at android.widget.ScrollView.requestLayout(ScrollView.java:1483)
        at android.view.View.requestLayout(View.java:17476)
        at android.view.ViewGroup.addView(ViewGroup.java:3784)
        at android.view.ViewGroup.addView(ViewGroup.java:3727)
        at android.view.ViewGroup.addView(ViewGroup.java:3700)
        at dev.atomtables.atomchat.MainActivity.onReceiveMessage(MainActivity.java:279)
        at dev.atomtables.atomchat.MainActivity.lambda$onCreate$4$dev-atomtables-atomchat-MainActivity(MainActivity.java:98)
        at dev.atomtables.atomchat.MainActivity$$ExternalSyntheticLambda5.call(D8$$SyntheticClass)
        at io.socket.emitter.Emitter.emit(Emitter.java:117)
        at io.socket.client.Socket.onevent(Socket.java:363)
        at io.socket.client.Socket.onpacket(Socket.java:307)
        at io.socket.client.Socket.access$100(Socket.java:19)
        at io.socket.client.Socket$2$2.call(Socket.java:92)
        at io.socket.emitter.Emitter.emit(Emitter.java:117)
        at io.socket.client.Manager.ondecoded(Manager.java:361)
        at io.socket.client.Manager.access$1200(Manager.java:22)
        at io.socket.client.Manager$5.call(Manager.java:355)
        at io.socket.parser.IOParser$Decoder.add(IOParser.java:103)
        at io.socket.client.Manager$2.call(Manager.java:331)
        at io.socket.emitter.Emitter.emit(Emitter.java:117)
        at io.socket.engineio.client.Socket.onPacket(Socket.java:556)
        at io.socket.engineio.client.Socket.access$1000(Socket.java:29)
        at io.socket.engineio.client.Socket$5.call(Socket.java:335)
y4ekin9u

y4ekin9u1#

问题不在这里。Emit导致它发送一条消息。该消息是在套接字库选择的线程上发出的。因此,您在套接字的线程上调用MainActivity.onRecieveMessage。您需要onRecieveMessage中的runOnUiThread,而不是在这里。从任何线程发出都是完美的。

相关问题