解决NetworkOnMainThreadException
今天在Android 访问 WebService 的时候遇到,错误Caused by: android.os.NetworkOnMainThreadException,查了下原因上在4.0之后在主线程里面执行Http请求都会报这个错,大概是怕Http请求时间太长造成程序假死的情况吧,于是就用另外一个线程处理请求,用的是handler机制,源码如下: package com.example.webservicetest; import java.io.IOException;
import java.io.UnsupportedEncodingException; import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException; import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast; @SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class MainActivity extends Activity { EditText editPara; EditText editRes; Button btnCal; Handler handler = null; /*
* @TargetApi(Build.VERSION_CODES.GINGERBREAD)
*
* @SuppressLint("NewApi")
*
* @Override
*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); /*
* if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy
* policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
* StrictMode.setThreadPolicy(policy); }
*/ handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle data = msg.getData();
String val = data.getString("value"); Toast.makeText(getApplicationContext(), "获取成功",
Toast.LENGTH_LONG);
editRes.setText(val);
Log.i("mylog", "请求结果-->" + val); }
};
InitView();
InitEvents();
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
} private void InitView() {
editPara = (EditText) findViewById(R.id.editCity);
editRes = (EditText) findViewById(R.id.editRes); btnCal = (Button) findViewById(R.id.btnCal); } private void InitEvents() {
btnCal.setOnClickListener(new OnClickListener() { @Override
public void onClick(View view) {
// TODO Auto-generated method stub Runnable runnable = new Runnable() {
@Override
public void run() {
//
// TODO: http request. String sCity = editPara.getText().toString(); SoapObject sResult = TestWs(sCity); try {
if (sResult == null) { Message msg = new Message();
Bundle data = new Bundle();
data.putString("value", "计算错误");
msg.setData(data);
handler.sendMessage(msg);
}
else
{
String sText = parseWeather(sResult); Message msg = new Message();
Bundle data = new Bundle();
data.putString("value", sText);
msg.setData(data);
handler.sendMessage(msg);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // }
}; new Thread(runnable).start(); /*
* String sCity = editPara.getText().toString();
*
* SoapObject sResult = TestWs(sCity);
*
* String sText; try { sText = parseWeather(sResult); if
* (sResult != null) { Toast.makeText(getApplicationContext(),
* "获取成功", Toast.LENGTH_LONG); editRes.setText(sText); } } catch
* (UnsupportedEncodingException e) { // TODO Auto-generated
* catch block e.printStackTrace(); }
*/ }
}); } private SoapObject TestWs(String sCity) { String NAMESPACE = "http://WebXml.com.cn/"; String URL = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx"; String METHODNAME = "getWeatherbyCityName"; String SOAP_ACTION = "http://WebXml.com.cn/getWeatherbyCityName"; SoapObject so = new SoapObject(NAMESPACE, METHODNAME); HttpTransportSE httpSE = new HttpTransportSE(URL);
httpSE.debug = true;
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11); soapEnvelope.dotNet = true;
soapEnvelope.bodyOut = so;
so.addProperty("theCityName", sCity);
soapEnvelope.setOutputSoapObject(so); try {
httpSE.call(null, soapEnvelope); SoapObject seOut = (SoapObject) soapEnvelope.getResponse(); return seOut; /*
* if(seOut!=null) { String sResult= (String)
* seOut.getProperty("getWeatherbyCityNameResult");
*
* return sResult;
*
* }
*/ } catch (HttpResponseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null; } private String parseWeather(SoapObject detail)
throws UnsupportedEncodingException {
String date = detail.getProperty(6).toString();
String weatherToday = "今天:" + date.split("")[0];
weatherToday = weatherToday + "\n天气:" + date.split("")[1];
weatherToday = weatherToday + "\n气温:"
+ detail.getProperty(5).toString();
weatherToday = weatherToday + "\n风力:"
+ detail.getProperty(7).toString() + "\n";
System.out.println("weatherToday is " + weatherToday); return weatherToday;
} }
解决NetworkOnMainThreadException的更多相关文章
- 解决android.os.NetworkOnMainThreadException
好久不写Android代码手都生了,找出自己之前写的程序发现跑不了了,也没啥特别的错误提示,就看到一句有用的错误Caused by: android.os.NetworkOnMainThreadExc ...
- 解决发http get请求的时候不成功,出现android.os.NetworkOnMainThreadException的异常
问题描述:在接游戏sdk的时候,由于游戏要求购买的时候是在主线程里面进行的,但是发http请求是不能在主线程里面发,否则就会出现android.os.NetworkOnMainThreadExcept ...
- android.os.NetworkOnMainThreadException异常如何解决
android.os.NetworkOnMainThreadException 08-08 17:53:30.635 I/ArticleTable(22461): 添加成功 58 08-08 17:5 ...
- Android记录10--android.os.NetworkOnMainThreadException异常解决办法
2013年11月1日小光棍节 有一段时间没有发表新的博客了,最近一直在忙着开发新浪微博客户端遇到很多问题比较头痛,比如说本篇博客要讲的NetworkOnMainThreadException这个异常, ...
- Android 关于“NetworkOnMainThreadException”出错提示的原因及解决办法
几乎每天都在论坛里面看到有网友问这个问题,代码是无误的,在低版本的API上都可以运行的,但在3.0以上的版本就会出现NetworkOnMainThreadException 出现android.os. ...
- Android Eclipseproject开发中的常见调试问题(二)android.os.NetworkOnMainThreadException 异常的解决的方法
android.os.NetworkOnMainThreadException 异常的解决的方法. 刚开是把HttpURLConnectionnection 打开连接这种方法放在UI线程里了,可能不是 ...
- [Android开发那点破事]解决android.os.NetworkOnMainThreadException
[Android开发那点破事]解决android.os.NetworkOnMainThreadException 昨天和女朋友换了手机,我的iPhone 4S 换了她得三星I9003.第一感觉就是好卡 ...
- 安卓开发解决android.os.NetworkOnMainThreadException异常方法(主线程不能直接调用webservice)
安卓开发解决android.os.NetworkOnMainThreadException异常方法 2013-01-07 14:01:04| 分类: 技术 | 标签:安卓 技术 java | ...
- 执行Socket socket = new Socket(ip, port);时抛出个异常:android.os.NetworkOnMainThreadException解决办法
首先,确认你的android版本是4.0之后再用此方法解决,因为在4.0之后在主线程里面执行Http请求才会报这个错,也许是怕Http请求时间太长造成程序假死的情况吧.Android在4.0之前的版本 ...
随机推荐
- iTween
http://u3d.as/content/pixelplacement/i-tween/1s9 download http://itween.pixelplacement.com/documenta ...
- 【Construct Binary Tree from Inorder and Postorder Traversal】cpp
题目: Given inorder and postorder traversal of a tree, construct the binary tree. Note:You may assume ...
- SQL Server性能优化(1)使用SET函数
在一切开始之前,先看下微软的建议:在系统的整体性能优化里面, TSQL优化优先级并不是最高的. 本文包括四部分: SET STATISTICS TIME ON SET STATISTICS IO SE ...
- C++ 11 新特性
C++11新特性: 1.auto 2.nullptr 3.for 4.lambda表达式 5.override ...
- JVM 崩溃 Failed to write core dump解决办法 WINDOWS
JVM 崩溃 Failed to write core dump解决办法 WINDOWS MIT key words: JVM,崩溃,windows,Failed,core dump,虚拟内存 最近从 ...
- 【BZOJ】【1863】【ZJOI2006】trouble 皇帝的烦恼
二分+DP Orz KuribohG 神题啊= = 满足单调性是比较显然的…… 然而蒟蒻并不会判断能否满足……QwQ 神一样的DP姿势:f[i]表示第 i 个与第1个最多有多少个相同,g[i]表示最少 ...
- C#指针与字节数组的操作
private static byte[] ReadBytesFromPtr(IntPtr intPtr, int bufferLength) { var result = new byte[buff ...
- 用c语言产生随机数的方法
用c语言产生随机数的方法 在C语言中,rand()函数可以用来产生随机数,但是这不是真正意义上的随机数,是一个伪随机数,是根据一个数,我们可以称它为种子,为基准以某个递推公式推算出来的一系数,当这系列 ...
- (转)Engineering Productivity
(转)http://www.wandoujia.com/blog/from-qa-to-ep 这个文章之前读过,很不错.今天再读,有不一样的感受!推荐下. 下面是几段摘录: EP 是什么 说到这里,E ...
- post 方式提交XML文件调用接口
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Date; import java. ...