android网络连接问题,android.os.NetworkOnMainThreadException异常

流水年华ye 2014-06-27 07:09:07
我已经将网络连接放到了线程中,怎么会还出现这个错,

...全文
629 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
jike0802 2014-07-16
  • 打赏
  • 举报
回复
android 4.0以后网络操作不能再主线程
妮_梦 2014-07-16
  • 打赏
  • 举报
回复
有几种方式解决,第一个是 new Thread(),第二个AsycnTask. 你现在虽然是有run方法。但是你是使用postdelay. 这个方法应该是在主线程运行的。所以才会出这个异常
Samson Bruce 2014-07-16
  • 打赏
  • 举报
回复
楼上基本上都说对了的,你可以通过Thread.currentThread().getId();去看你runnable里面的id和外面的UI线程的ID是否一样。就确切知道你没有将耗时的网络操作放到非主线程中去工作了。
baidu_16117309 2014-07-16
  • 打赏
  • 举报
回复
并没有开启新线程,只是加入到当前线程的消息队列中
云上飞翔 2014-07-16
  • 打赏
  • 举报
回复
引用 楼主 dy12011023 的回复:
我已经将网络连接放到了线程中,怎么会还出现这个错,
1)网络代码不能在GUI主线程中执行。 2)楼主错误在于:XXX.postDelayed(new Runnable(){}),虽然new Runnable(){网络代码} ,但这不是一个线程,只是一个实现了Runnable接口的对象。然后:这个网络代码是通过postDelayed()方法还是提交给GUI主线程来做的。这就是错误的根源。
baidu_16117309 2014-07-16
  • 打赏
  • 举报
回复
handler.postdelay()都是运行在ui线程中
baidu_16117309 2014-07-16
  • 打赏
  • 举报
回复
handler.post(Runnable())及handler.post
流水年华ye 2014-07-15
  • 打赏
  • 举报
回复
引用 1 楼 hjywyj 的回复:
你哪放线程中了? new Thread(new Runable(){ /*联网获取数据*/ }).start();
postdelay()方法中的2个参数,用你这个不行呀,
mybeta 2014-06-30
  • 打赏
  • 举报
回复
像post这些方法一般都是放到主线程执行的
山雨楼 2014-06-30
  • 打赏
  • 举报
回复
android 自带 的AsyncTask 这个方法,可以试试
fu_zhen 2014-06-29
  • 打赏
  • 举报
回复
boolean android.view.View.postDelayed(Runnable action, long delayMillis) Causes the Runnable to be added to the message queue, to be run after the specified amount of time elapses. The runnable will be run on the user interface thread. Parameters: action The Runnable that will be executed. delayMillis The delay (in milliseconds) until the Runnable will be executed. Returns: true if the Runnable was successfully placed in to the message queue. Returns false on failure, usually because the looper processing the message queue is exiting. Note that a result of true does not mean the Runnable will be processed -- if the looper is quit before the delivery time of the message occurs then the message will be dropped. See Also: post removeCallbacks
jeky_zhang2013 2014-06-29
  • 打赏
  • 举报
回复
android里面好像还要设置handler处理类
奋斗中的显摆 2014-06-29
  • 打赏
  • 举报
回复
引用 2 楼 dy12011023 的回复:
[quote=引用 1 楼 hjywyj 的回复:] 你哪放线程中了? new Thread(new Runable(){ /*联网获取数据*/ }).start();
我new Runable(){}这个方法不是在线程中?[/quote] runable是一个以过程方法函数,你使用Handle.postdelay;是指在一定时间之后去执行这个方法!thread才是线程! 你按照1楼的写法就可以了
流水年华ye 2014-06-28
  • 打赏
  • 举报
回复
引用 1 楼 hjywyj 的回复:
你哪放线程中了? new Thread(new Runable(){ /*联网获取数据*/ }).start();
我new Runable(){}这个方法不是在线程中?
  • 打赏
  • 举报
回复
你哪放线程中了? new Thread(new Runable(){ /*联网获取数据*/ }).start();

80,359

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧