解决NetworkOnMainThreadException

简介: 今天在Android 访问 WebService 的时候遇到,错误Caused by: android.os.NetworkOnMainThreadException,查了下原因上在4.0之后在主线程里面执行Http请求都会报这个错,大概是怕Http请求时间太长造成程序假死的情况吧,于是就用另外一个线程处理请求,用的是handler机制,源码如下:package com.
今天在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; } }

 

相关文章
|
1月前
|
缓存 Java 数据库
Android的ANR原理
【10月更文挑战第18天】了解 ANR 的原理对于开发高质量的 Android 应用至关重要。通过合理的设计和优化,可以有效避免 ANR 的发生,提升应用的性能和用户体验。
59 8
|
Java Shell Android开发
Android 11 ANR
Android 11 ANR
410 0
Android 11 ANR
|
数据库
读取数据库的照片和视频报android.os.NetworkOnMainThreadException
读取数据库的照片和视频报android.os.NetworkOnMainThreadException
79 0
读取数据库的照片和视频报android.os.NetworkOnMainThreadException
|
Java 数据库 Android开发
android ANR产生原因和解决办法
android ANR产生原因和解决办法
Caused by: android.os.NetworkOnMainThreadException
问题: Caused by: android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.
2088 0
|
API Android开发
Android 关于“NetworkOnMainThreadException”出错提示的原因及解决办法
代码是无误的,在低版本的API上都可以运行的,但在3.0以上的版本就会出现 NetworkOnMainThreadException 出现Android.
2187 0
|
XML Android开发 数据格式
Android 7.0 调取系统相机崩溃解决android.os.FileUriExposedException
写在前面 最近由于廖子尧忙于自己公司的事情和 OkGo (一款专注于让网络请求更简单的网络框架) ,故让LZ 接替维护 ImagePicker(一款支持单、多选、旋转和裁剪的图片选择器),也是处理了诸多bug,最近总算趋于稳定了,这里就把 Android N (API 24) 以上的相机适配方案分享给大家。
1157 0