• NetworkOnMainThreadException


    来自:http://www.2cto.com/kf/201402/281526.html

    NetworkOnMainThreadException

    extends RuntimeException

    java.lang.Object
    ? java.lang.Throwable
      ? java.lang.Exception
        ? java.lang.RuntimeException
          ? android.os.NetworkOnMainThreadException

    Class Overview


    The exception that is thrown when an application attempts to perform a networking operation on its main thread.

    This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing for Responsiveness.

    Also see StrictMode.


    所以事情就很清楚了。一个APP如果在主线程中请求网络操作,将会抛出此异常。Android这个设计是为了防止网络请求时间过长而导致界面假死的情况发生。

    解决方案有两个,一个是使用StrictMode,二是使用线程来操作网络请求。

    第一种方法:简单暴力,强制使用,代码修改简单(但是非常不推荐)
    在MainActivity文件的setContentView(R.layout.activity_main)下面加上如下代码

     
    1
    2
    3
    4
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }


    第二种方法就是我使用的方法也是我要推荐的方法,将请求网络资源的代码使用Thread去操作。在Runnable中做HTTP请求,不用阻塞UI线程。

     
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.main_view);
        new Thread(runnable).start();
    }
     
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("value");
            Log.i(TAG,"请求结果:" + val);
        }
    }
     
    Runnable runnable = new Runnable(){
        @Override
        public void run() {
            // TODO: http request.
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("value","请求结果");
            msg.setData(data);
            handler.sendMessage(msg);
        }
    }


    上面是比较通用的方法,我的代码:

     
    1
    2
    3
    4
    5
    6
    7
    8
    // Android 4.0 之后不能在主线程中请求HTTP请求
                new Thread(new Runnable(){
                    @Override
                    public void run() {
                        cachedImage = asyncImageLoader.loadDrawable(imageUrl, position);
                        imageView.setImageDrawable(cachedImage);
                    }
                }).start();                         
  • 相关阅读:
    ionic + cordova+angularJs 搭建的H5 App完整版总结
    在DevExpress程序中使用GridView直接录入数据的时候,增加列表选择的功能
    【Web动画】SVG 线条动画入门
    闲来无聊,研究一下Web服务器 的源程序
    PHP实现RTX发送消息提醒
    关于AngularJS(1)
    项目总结12:bootstrap-select下拉框模糊搜索
    JAVA读取XML文件并解析获取元素、属性值、子元素信息
    项目总结11:Centos部署JDK+Tomcat+MySQL文档(阿里云-网易云-华为云)
    项目总结10:通过反射解决springboot环境下从redis取缓存进行转换时出现ClassCastException异常问题
  • 原文地址:https://www.cnblogs.com/qhyhao/p/3625225.html
Copyright © 2020-2023  润新知