用输入输出流实现往sdcard下载apk文件时,下载到途中程序闪退,有时候下载到28%,有时候到6%,每次不同,但都下载不成功程序就停止运行了。apk文件大小为10M,手机卡上的容量有300多M。代码如下:
public File getFileFromServer(String path, ProgressDialog pd) throws Exception{
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
pd.setMax(conn.getContentLength());
InputStream is = conn.getInputStream();
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
}
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "updata.apk");
FileOutputStream fos = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int len ;
int total=0;
while((len =bis.read(buffer)) > 0){
fos.write(buffer, 0, len);
total+= len;
//获取当前下载量
pd.setProgress(total);
}
fos.flush();
bis.close();
is.close();
return file;
}
else{
return null;
}
}