我正在使用“Web套接字”测试聊天服务
代码不会出错。但是,当我在应用程序中午餐时,它甚至无法启动
错误
06-10 16:59:22.420: E/AndroidRuntime(10814): FATAL EXCEPTION: main
06-10 16:59:22.420: E/AndroidRuntime(10814): java.lang.RuntimeException: Unable to resume activity {com.websocketchat_test/com.websocketchat_test.WebsocketChat}: android.os.NetworkOnMainThreadException
06-10 16:59:22.420: E/AndroidRuntime(10814): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2466)
06-10 16:59:22.420: E/AndroidRuntime(10814): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2494)
06-10 16:59:22.420: E/AndroidRuntime(10814): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2008)
06-10 16:59:22.420: E/AndroidRuntime(10814): at android.app.ActivityThread.access$600(ActivityThread.java:123)
06-10 16:59:22.420: E/AndroidRuntime(10814): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1169)
我的主要代码在这里..
public class WebsocketChat extends Activity implements View.OnClickListener{
private static String SERVER_HOST = "10.0.0.1";
private WebSocket websocket;
private EditText messageEditText;
private TextView logsTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
messageEditText = (EditText)this.findViewById(R.id.messageEditText);
logsTextView = (TextView)this.findViewById(R.id.logsTextView);
try {
URI url = new URI("ws://" + SERVER_HOST + "/");
websocket = new WebSocketConnection(url);
websocket.setEventHandler(new WebSocketEventHandler() {
Handler handler = new Handler();
public void onOpen() {
updateLog("connected.");
}
public void onMessage(final WebSocketMessage message) {
handler.post(new Runnable() {
public void run() {
updateLog(message.getText().trim());
}
});
}
public void onClose() {
updateLog("closed");
}
});
View sendButton = this.findViewById(R.id.sendButton);
sendButton.setOnClickListener(this);
} catch (WebSocketException wse) {
wse.printStackTrace();
} catch (URISyntaxException use) {
use.printStackTrace();
}
}
@Override
public void onResume() {
super.onResume();
try {
websocket.connect();
} catch (WebSocketException wse) {
wse.printStackTrace();
}
}
public void onClick(View view) {
try {
websocket.send(messageEditText.getText().toString());
messageEditText.setText("");
} catch (WebSocketException wse) {
wse.printStackTrace();
}
}
private void updateLog(String message) {
logsTextView.setText("> " + message + "\n" + logsTextView.getText());
}
}
我不知道为什么会这样。我确实添加了互联网许可.. 任何建议都可以。请回复。
答案 0 :(得分:0)
最近的Android版本不允许主/ UI线程上的任何网络活动。您可以查看AutobahnAndroid - 一个Android / Java WebSocket实现,它可以在后台线程上完成所有网络连接。
披露:我是Autobahn的原作者,并为Tavendo工作。