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() {
// 精神恢复满了
// 元气恢复满了
// 抽美人时间到了-百里,万里
// 活动吃鸡
// 打牛活动开启
for( int 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();
}
}
}