解决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之前的版本 ...
随机推荐
- python操作sqlite数据库
root@cacti:~/box# cat convert.py #!/usr/bin/env python import sqlite3,time,rrdtool,os def boxstatus( ...
- mac下phpstorm左侧的project列表找不到了
早上开机,发现左侧的project列表没有了,用着不方便,当然了,是可以调出来的. View-Tool Windows-Project,就出来来. 快捷键:command+1. 问题解决.
- Least Common Ancestors 分类: ACM TYPE 2014-10-19 11:24 84人阅读 评论(0) 收藏
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #i ...
- [noip2005提高]过河 dp
由于L的范围到了109,用普通dp做肯定是不成了: 可以观察到M的数量很小,dp在转移的过程中有大量的无用转移: 可以想到压缩范围,问题是如何压缩,观察若S=9,T=10时,能到达的点,9,10,18 ...
- Nodejs Express 4.X 中文API 2--- Request篇
相关阅读: Express 4.X API 翻译[一] -- Application篇 Express4.XApi 翻译[二] -- Request篇 Express4.XApi 翻译[三] -- ...
- .NET设计模式(11):组合模式(Composite Pattern)(转)
概述 组合模式有时候又叫做部分-整体模式,它使我们树型结构的问题中,模糊了简单元素和复杂元素的概念,客户程序可以向处理简单元素一样来处理复杂元素,从而使得客户程序与复杂元素的内部结构解耦. 意图 将对 ...
- xmlns与targetNamespace
xmlns与targetNamespace xmlns与targetNamespacehttp://blog.sina.com.cn/weatry在使用XML Schema生成XML文件时,我们常常会 ...
- dojo简单添加一个Panel到父容器中
this.contentPane = new ContentPane(); this.set("content", this.contentPane.domNode); this. ...
- logback日志项目使用方法 - 150205交易模块添加日志信息logback,orderNo订单号为log主键便于跟踪,数字常量化,解决取消支付BUG,弱网络环境原因
1.项目里面的日志,便于跟踪数据的变更和异常错误信息产生.生产环境的日志级别是INFO,测试环境日志级别DEBUG,如果生产环境的日志级别是DEBUG,虽然方便查询问题,可以看到SQL语句等信息,但是 ...
- js获取服务器时间
Ajax HTTP Head法原理:一般服务器在发送静态页面的时候(apache, nginx, lighttpd就目前所知)都是会在 HTTP 头里带一个Date的头信息的,那么我用Ajax直接取头 ...