zoukankan      html  css  js  c++  java
  • android.os.NetworkOnMainThreadException

        在android 2.3上设计的下载程序,在android 4.0上运行时报android.os.NetworkOnMainThreadException异常,原来在4.0中,访问网络不能在主程序中进行,有两个方法可以解决,一个是在主程序中增加:

            // 详见StrictMode文档
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                    .detectDiskReads()
                    .detectDiskWrites()
                    .detectNetwork()   // or .detectAll() for all detectable problems
                    .penaltyLog()
                    .build());
            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                    .detectLeakedSqlLiteObjects()
                    .detectLeakedClosableObjects()
                    .penaltyLog()
                    .penaltyDeath()
                    .build());

    同时还需要加两行代码

    /* 在文件头部加引入 */
    import android.os.StrictMode;
    
    在类前加入
    @SuppressLint("NewApi") 

     另一种是启动线程执行下载任务:

        public void onCreate(Bundle savedInstanceState) {

     1         super.onCreate(savedInstanceState);
     2         setContentView(R.layout.main);
     3         // 启动线程执行下载任务
     4         new Thread(downloadRun).start();
     5     }
     6     
     7     /**
     8      * 下载线程
     9      */
    10     Runnable downloadRun = new Runnable(){
    11 
    12         @Override
    13         public void run() {
    14             // TODO Auto-generated method stub
    15             updateListView();
    16         }
    17     };
  • 相关阅读:
    junit4
    spring
    hibernate 的注意事项
    Struts2 的 命名规范
    Struts2 的标签
    OGNL
    添加删除 板块 struts2
    Struts2 的各种xml 和struts 配置信息 都是一样的
    struts2
    struts2
  • 原文地址:https://www.cnblogs.com/cfox/p/3026650.html
Copyright © 2011-2022 走看看