zoukankan      html  css  js  c++  java
  • 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();                         
  • 相关阅读:
    模拟城市:我是市长
    IOTA私有链简单搭建
    SOUL软件小结
    ubuntu 16.04 安装node.js 8.x
    Ubuntu下Hyperledger Fabric v0.6安装部署
    区块链关键术语与概念
    Windows Server 2019安装OpenSSH Server简明教程
    Windows10和Windows Server 2019支持OpenSSH
    TypeError: __init__() got an unexpected keyword argument 'serialized_options'
    无法从路径’NuGet.CommandLine.2.7.1.nupkg’读取包
  • 原文地址:https://www.cnblogs.com/qhyhao/p/3625225.html
Copyright © 2011-2022 走看看