解决NetworkOnMainThreadException

时间:2023-03-11 21:11:44
今天在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;
} }