今天在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的更多相关文章

  1. 解决android.os.NetworkOnMainThreadException

    好久不写Android代码手都生了,找出自己之前写的程序发现跑不了了,也没啥特别的错误提示,就看到一句有用的错误Caused by: android.os.NetworkOnMainThreadExc ...

  2. 解决发http get请求的时候不成功,出现android.os.NetworkOnMainThreadException的异常

    问题描述:在接游戏sdk的时候,由于游戏要求购买的时候是在主线程里面进行的,但是发http请求是不能在主线程里面发,否则就会出现android.os.NetworkOnMainThreadExcept ...

  3. android.os.NetworkOnMainThreadException异常如何解决

    android.os.NetworkOnMainThreadException 08-08 17:53:30.635 I/ArticleTable(22461): 添加成功 58 08-08 17:5 ...

  4. Android记录10--android.os.NetworkOnMainThreadException异常解决办法

    2013年11月1日小光棍节 有一段时间没有发表新的博客了,最近一直在忙着开发新浪微博客户端遇到很多问题比较头痛,比如说本篇博客要讲的NetworkOnMainThreadException这个异常, ...

  5. Android 关于“NetworkOnMainThreadException”出错提示的原因及解决办法

    几乎每天都在论坛里面看到有网友问这个问题,代码是无误的,在低版本的API上都可以运行的,但在3.0以上的版本就会出现NetworkOnMainThreadException 出现android.os. ...

  6. Android Eclipseproject开发中的常见调试问题(二)android.os.NetworkOnMainThreadException 异常的解决的方法

    android.os.NetworkOnMainThreadException 异常的解决的方法. 刚开是把HttpURLConnectionnection 打开连接这种方法放在UI线程里了,可能不是 ...

  7. [Android开发那点破事]解决android.os.NetworkOnMainThreadException

    [Android开发那点破事]解决android.os.NetworkOnMainThreadException 昨天和女朋友换了手机,我的iPhone 4S 换了她得三星I9003.第一感觉就是好卡 ...

  8. 安卓开发解决android.os.NetworkOnMainThreadException异常方法(主线程不能直接调用webservice)

    安卓开发解决android.os.NetworkOnMainThreadException异常方法 2013-01-07 14:01:04|  分类: 技术 |  标签:安卓  技术  java  | ...

  9. 执行Socket socket = new Socket(ip, port);时抛出个异常:android.os.NetworkOnMainThreadException解决办法

    首先,确认你的android版本是4.0之后再用此方法解决,因为在4.0之后在主线程里面执行Http请求才会报这个错,也许是怕Http请求时间太长造成程序假死的情况吧.Android在4.0之前的版本 ...

随机推荐

  1. “来用”alpha版使用说明书

    1引言 1 .1编写目的 针对我们发布的alpha版本做出安装和使用说明,使参与内测的人员及用户了解软件的使用方法和相关内容. 1 .2参考资料 <c#程序设计基础>,赵敏主编,2011, ...

  2. UVA - 11478 Halum 二分+差分约束

    题目链接: http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=34651 题意: 给定一个有向图,每一条边都有一个权值,每次你可以 ...

  3. 关于Web服务器域名设置相关知识积累

    1.第一个问题,如何将一个服务器映射到一个域名上呢?    在申请域名的时候,会配置服务器IP和域名的对应关系,所以如果系统中只有一个应用的情况下,应用服务器不需要做任何配置. 2.在Tomcat服务 ...

  4. 【Lua】Lua中__index与元表(转)

    转载于:http://blog.csdn.net/xocoder/article/details/9028347 Lua的表本质其实是个类似HashMap的东西,其元素是很多的Key-Value对,如 ...

  5. 【BZOJ】【3831】【POI2014】Little Bird

    DP/单调队列优化 水题水题水题水题 单调队列优化的线性dp…… WA了8次QAQ,就因为我写队列是[l,r),但是实际操作取队尾元素的时候忘记了……不怎么从队尾取元素嘛……平时都是直接往进放的……还 ...

  6. shadowmap 及优化

    对于子阴影的走样, 条纹 开zbias resterizeState zbias = 1000...大概这样 另一个方法是画背面 backface是指一个人肚子那面,后背那面 而不是肚子的里面那层 所 ...

  7. 使用命令行进行 VS单元测试 MSTest

    测试 指定的方法 "D:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\MSTest.exe" /test ...

  8. IO端口和IO内存

    为什么会有IO端口和IO内存 这主要原因是因为处理器的架构不同,这里我们使用arm来代表典型的使用IO内存架构,intel 80x86代表典型的使用IO端口架构.简单来说arm把所有寄存器(包括外部设 ...

  9. mybatis中:returned more than one row, where no more than one was expected.异常

    org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.executor.ExecutorEx ...

  10. appium获取android app的包名和主Activity

    方法一在appium的android setting中选择下载到电脑上的app包,获取Activity. 方法二在android-sdk中安装build-tools包,进入这个目录.aapt dump ...