zoukankan      html  css  js  c++  java
  • 主线程中一定不能放耗时操作,必须要开子线程,比如下载文件,不然会不让你拿到输入流--报错显示android.os.NetworkOnMainThreadException

    1.必须要开子线程来操作耗时操作,android.os.NetworkOnMainThreadException

    new Thread(new Runnable() {
    			
    			@Override
    			public void run() {
    				// TODO Auto-generated method stub
    				try {
    					updateFile = Environment.getExternalStorageDirectory()
    							+ "/3530.jpg";
    					//downloadUpdateFile("http://image.anzimall.com/3530/3530_K21D_app_V2.3_2015050528.bin",  updateFile);
    					downloadUpdateFile("http://img1.cache.netease.com/catchpic/F/FC/FCC085159B92C5EE4FDDB9618166051E.jpg",  updateFile);
    				} catch (Exception e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();  //android.os.NetworkOnMainThreadException
    					System.out.println(e.toString()+"");
    				}
    			}
    		}).start();
    

    2.抛出异常之后一定要打印异常,看看异常的具体信息。System.out.println(e.toString()+"");

    
    
    public static long downloadUpdateFile(String down_url, String file)
    			throws Exception {
    
    		int downloadCount = 0;// 已经下载好的大小
    
    		InputStream inputStream;
    		OutputStream outputStream;
    		URL url = new URL(down_url);
    		HttpURLConnection httpurlconnection = (HttpURLConnection) url
    				.openConnection();
    		httpurlconnection.setConnectTimeout(5000);
    		httpurlconnection.setReadTimeout(5000);
    		// 获取下载文件的size
    		//totalSize = httpURLConnection.getContentLength();
    
    		if (httpurlconnection.getResponseCode() == 404) {
    			throw new Exception("fail!");
    			// 这个地方应该加一个下载失败的处理,但是,因为我们在外面加了一个try---catch,已经处理了Exception,
    			// 所以不用处理
    		}
    
    		inputStream = httpurlconnection.getInputStream();
                    File file_ok = new File(file);
    		outputStream = new FileOutputStream(file_ok);// 文件存在则覆盖掉
    
    		byte buffer[] = new byte[1024];
    		int readsize = 0;
    
    		while ((readsize = inputStream.read(buffer)) != -1) {
    			outputStream.write(buffer, 0, readsize);
    			downloadCount += readsize;// 时时获取下载到的大小
    		}
    		if (httpurlconnection != null) {
    			httpurlconnection.disconnect();
    		}
    		inputStream.close();
    		outputStream.close();
    
    		return downloadCount;
    	}
    

      

  • 相关阅读:
    java设计模式之代理模式 ,以及和java 回调机制的区别
    oracle 安装,启动 ,plsql 连接
    jsp 访问文件夹中的图片,tomcat配置虚拟目录
    最实用解决tomcat startup.bat 一闪而过
    oracle 创建表
    java debug源码完整版
    node.js事件轮询(1)
    markdown命令语法
    mac常用的命令
    node + nginx + mongo搭建负载均衡
  • 原文地址:https://www.cnblogs.com/childhooding/p/4664762.html
Copyright © 2011-2022 走看看