您的位置:首页 > 理论基础 > 计算机网络

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

2015-07-22 16:04 549 查看
此错误是因为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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: