博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
解决NetworkOnMainThreadException
阅读量:4690 次
发布时间:2019-06-09

本文共 7078 字,大约阅读时间需要 23 分钟。

今天在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;    }}

 

转载于:https://www.cnblogs.com/zuiyirenjian/p/4199365.html

你可能感兴趣的文章
信息模型之项目域
查看>>
第二十三模板 18.3.4多重集合 multiset
查看>>
Hibernate4.3配置
查看>>
[原]Ubuntu 下安装apache+PHP
查看>>
妙味——getByClass
查看>>
JavaScript 严格模式(use strict)
查看>>
Hibernate学习笔记
查看>>
Java接口
查看>>
HTML5 初步了解
查看>>
在CI框架中的配置整合amfphp
查看>>
蓝桥杯 ——无重复组合——C++
查看>>
React Native在开发过程中遇到的一些问题(俗称:坑)
查看>>
自控力阅读思维导图
查看>>
结构体的应用-成绩录入初步
查看>>
【UVa 712】S-Trees
查看>>
一次MySQL(INNODB存储引擎) 死锁捉虫记
查看>>
python urllib、urlparse、urllib2、cookielib
查看>>
ListBox和ComboBox绑定数据简单例子
查看>>
QQ聊天窗口上的广告与QQ弹窗广告的完美屏蔽去除
查看>>
weblogic连接池问题总结(转载)
查看>>