解决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; } }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值