异常:android.os.NetworkOnMainThreadException

Android 4.1项目:使用新浪微博分享时报:

  android.os.NetworkOnMainThreadException

网上搜索后知道是因为版本问题,在4.0之后在主线程里面执行Http请求都会报这个错,也许是怕Http请求时间太长造成程序假死的情况吧。那么网上的朋友也给出了相应的解决方案,这叫上有政策下有对策:那就是另起线程去发http请求

public void allNtfInit() {

             try {

                   url = new URL("http://115.236.18.194:8082/servercontrller/test" );

            } catch (MalformedURLException e) {

                  e.printStackTrace();

            }

             new Thread( new Runnable() {                

                   @Override

                   public void run() {

//                      精神恢复满了

//                      元气恢复满了

//                      抽美人时间到了-百里,万里     

//                      活动吃鸡

//                      打牛活动开启

                         forint i = 0;i<= 5;i++){

                              sentHttp(i);

                        }

                  }

            }).start();

      }

public void sentHttp( int type) {

             //获得skyid ,roleid,serverid,类型

             int skyid = 0;

             int roleid = 0;

             int serverid = 0;

             try {

                  String message = new String();

                   httpURLConn = (HttpURLConnection) url.openConnection();

                   httpURLConn.setDoOutput( true);

                   httpURLConn.setDoInput( true);

                   httpURLConn.setRequestMethod( "POST");

                   httpURLConn.setConnectTimeout(1000);

                  String content= "skyid="+skyid;

                  content += "&roleid="+roleid;

                  content += "&serverid="+serverid;

                  content += "&type="+type;

                   httpURLConn.getOutputStream().write( content.getBytes() );

                   httpURLConn.connect();

                  InputStream in = httpURLConn.getInputStream();

                  BufferedReader bd = new BufferedReader( new InputStreamReader(in));

                   while ((message = bd.readLine()) != null) {

                        Log. e("返回结果" , message);

                        showNotification(message,type);

                  }

            } catch (Exception e) {

                  e.printStackTrace();

                  Log. e("Exception e" , e.toString());

            } finally {

                   if ( httpURLConn != null) {

                         httpURLConn.disconnect();

                  }

            }

      }

 

转载于:https://my.oschina.net/ffse54s/blog/783254

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值