Android用HTTP下载报错“android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork”

本文介绍了一种解决Android应用中主线程访问网络限制的方法,通过开启新线程进行网络请求并下载文件到SD卡的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

此错误是因为Android不能在主线程中访问网络导致,可将访问网络代码另启线程运行:

Runnable r = new Runnable() {
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			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 exception
			e.printStackTrace();
		} catch (IOException e) {
			// TODO: handle exception
				e.printStackTrace();
			} 

		}
	};
	new Thread(r).start();
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值