Android Socket编程报错android.os.NetworkOnMainThreadException

在学习socket编程中,在主线程中初始化socket实例,创建子线程处理获取返回数据,利用handler返回消息给主线程,可是在运行的过程中,程序出错,错误信息如下:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sockettext/com.example.sockettext.PayActivity}: android.os.NetworkOnMainThreadException

Caused by: android.os.NetworkOnMainThreadException

经过查找相关资料了解到,造成这样的错误原因是代码不符合Android规范,如果把socket访问方式改为异步操作就不会出现在4.0上访问出现 android.os.NetworkOnMainThreadException异常,所以解决这个问题的方法有两个:

1、在异步操作中处理socket

2、从 Android 2.3 开始提供了一个新的类 StrictMode,该类可以用于捕捉发生在应用程序主线程中耗时的磁盘、网络访问或函数调用,可以帮助开发者改进程序,使主线程处理 UI 和动画在磁盘读写和网络操作时变得更平滑,避免主线程被阻塞。

所以可以在主线程中,setContent()后面加上一段代码


if (android.os.Build.VERSION.SDK_INT > 9) {
   StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() 
            .detectDiskReads().detectDiskWrites().detectNetwork() 
            .penaltyLog().build()); 
 
   StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() 
            .detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath() 
            .build());
  }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这个错误通常是由于在 WebSocket 连接已关闭的情况下,尝试发送或接收消息。为了防止这个错误,你可以在发送消息之前检查 WebSocket 连接的状态,如果连接已关闭,则不发送消息。下面是一个修改后的示例: ```python import websocket import threading class WebSocketClient: def __init__(self, url): self.url = url self.ws = None self.connect() def connect(self): self.ws = websocket.WebSocketApp(self.url, on_open=self.on_open, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close) self.wst = threading.Thread(target=self.ws.run_forever) self.wst.daemon = True self.wst.start() def on_open(self, ws): print("WebSocket connection established") def on_message(self, ws, message): print("Received message:", message) def on_error(self, ws, error): print("WebSocket error:", error) def on_close(self, ws): print("WebSocket connection closed") def send(self, message): if self.ws and self.ws.sock and self.ws.sock.connected: self.ws.send(message) else: print("WebSocket connection is closed.") def close(self): self.ws.close() if __name__ == "__main__": ws = WebSocketClient("ws://localhost:8080") ws.send("Hello, WebSocket Server!") ``` 在 `send` 方法中,我们添加了一些代码来检查 WebSocket 连接的状态。如果连接已关闭,则不发送消息,并打印一条错误信息。这样,在尝试发送消息之前,我们始终会检查 WebSocket 连接的状态,从而避免出现 `WebSocketConnectionClosedException` 异常。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值