解决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之前的版本 ...
随机推荐
- 阴影 box-shadow(二)
阴影 box-shadow(二) 1.阴影模糊半径与阴影扩展半径的区别 阴影模糊半径:此参数可选,其值只能是为正值,如果其值为0时,表示阴影不具有模糊效果,其值越大阴影的边缘就越模糊: 阴影扩展半径: ...
- jQuery插件开发总结
jQuery插件的开发包括两种: 一种是类级别的插件开发$.extend,即给jQuery添加新的全局函数,相当于给jQuery类本身添加方法,比如:$.ajax, $.getJSON等.jQuery ...
- quartz2D简单使用
quartz2D绘图 1:上下文:context,这个翻译不好理解,其实翻译环境更好一点,就是给了你一个画板,你看不到而已 在: CGContextRef ctx = UIGraphicsGetCur ...
- 这个好像、也许、或许、大概、应该、Maybe真的可以算是传说中的Spring.Net了吧
这个好像.也许.或许.大概.应该.Maybe真的可以算是传说中的Spring.Net了吧 ...
- 增强学习————K-摇臂赌博机
探索与利用增强学习任务的最终奖赏是在多步动作之后才能观察到,于是我们先考虑最简单的情形:最大化单步奖赏,即仅考虑一步操作.不过,就算这样,强化学习仍与监督学习有显著不同,因为机器要通过尝试来发现各个动 ...
- input.nextLine() 问题出错!
今天在学习关于I/O的知识的时候发现了一个小问题! 代码如下 package com.paulo.testio; import java.io.File; import java.io.IOExcep ...
- gvim编辑文件到github乱码
with below _vimrc settings, code uploaded to GitHub will display with proper encoding set encoding=u ...
- GS玩家登录
玩家上线 这个过程看了很多很多次了,这里在看下 客户端打开,服务器收到libevent事件,然后new Channel这个过程都付给他各种指针,然后放到channel容器中 .客户端发送c2s_log ...
- IIS Express 及 vs2008下使用IIS Express
介绍 IIS Express 开发 ASP.NET 的应用程序是我的主要工作.当然我会选择最适合的开发环境.客户多属于企业用户,我的开发的选择,多半是 ASP.NET Web Application ...
- AngularJs学习笔记--Guide教程系列文章索引
在很久很久以前,一位前辈向我推荐AngularJs.但当时我没有好好学习,仅仅是讲文档浏览了一次.后来觉醒了……于是下定决心好好理解这系列的文档,并意译出来(英文水平不足……不能说是翻译,有些实在是看 ...