Android用HTTP下载报错“android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork”
16lz
2021-01-23
此错误是因为Android不能在主线程中访问网络导致,可将访问网络代码另启线程运行:
Runnable r = new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtry {URL url = new URL(strURL);HttpURLConnection conn = (HttpURLConnection)url.openConnection();String path = "file";String fileName = fileNa + "." + fileEx;OutputStream output = null;/*获取SD卡路径*/String SDCard = "/mnt/sdcard/HTTPget"; //Environment.getExternalStorageDirectory()+"";System.out.println(SDCard);String pathName = SDCard + "/" + path + "/" + fileName; //文件保存路径File file = new File(pathName);InputStream input = conn.getInputStream();if(file.exists()){System.out.println("file exits");return;}else{String dir = SDCard + "/" + path;new File(dir).mkdirs(); //创建文件夹file.createNewFile(); //创建文件output = new FileOutputStream(file);byte[] buffer = new byte[4096];int len;while((len = input.read(buffer)) != -1){output.write(buffer, 0, len);}output.flush();}} catch (MalformedURLException e) {// TODO: handle exceptione.printStackTrace();} catch (IOException e) {// TODO: handle exceptione.printStackTrace();} }};new Thread(r).start();}
更多相关文章
- android读取plist文件
- 使用Android自带的DownloadManager下载文件
- android 获取.thumbnail文件下的小图标
- Android--用Pull解析器将对象解析成xml文件及单元测试
- android 反射解析xml文件成为java对象
- Android检查网络是否连接
- android 9.png 文件
- Android连接到加密网络
- Android TXT文件读写