使用HttpUrlConnection下载网络图片并显示
1.这里创建了一个异步类,便于其他地方的引用,继承AsyncTask;
2.doInBackground方法,在子线程中进行耗时操作,也就是获取图片的操作;
3.需要创建两个对象:
private String dirPath; //下载图片的目录 /root/pic/
private String filePath; //文件存储的具体位置 /root/pic/a.jpg
用于存放获取到的图片;
4.在子线程中进行进行判断:
if (!dir.exists()){
dir.mkdir();
}
//判断文件是否存在,若不存在,创建文件
filePath = dirPath+filename;
File file = new File(filePath);
if (file.exists()){
return -1;
}else{
try {
file.createNewFile(); //不存在,就创建这个文件
} catch (IOException e) {
e.printStackTrace();
}
}
如果文件夹不存在,就进行创建的操作;
5.然后进行输入流的获取,使用HttpUrlConnection读取网站图片:
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
URL url = new URL(strings[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (connection.getResponseCode() == 200){
//判断返回码是否正常,若正常创建输入流,否则就直接返回
inputStream = connection.getInputStream();
}else{
return -2;
}
outputStream= new FileOutputStream(file);
int length = 0;
byte[] buffer = new byte[4*1024];
while ((length = inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
这里,如果读取正常,返回码是200,则正常,如果为其他出错了。
6.在onPostExecute,也就是主线程中进行UI更新:
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
switch (integer){
case 1:
//正常下载完成
Toast.makeText(context,"下载完成",Toast.LENGTH_SHORT).show();
Bitmap bm = BitmapFactory.decodeFile(filePath);
loadImg.setImageBitmap(bm);
break;
case -1:
//文件已存在
Toast.makeText(context,"文件已存在",Toast.LENGTH_SHORT).show();
break;
case -2:
//网络异常
Toast.makeText(context,"网络异常",Toast.LENGTH_SHORT).show();
break;
}
}
7.回到Activity中,在监听里获取图片的地址:
new PicLoadTask(PicActivity.this,loadImg).execute(picUrl,"pg12.jpg");
再次运行时,需要修改图片名。
8.如果是6.0以上的模拟器,需要添加动态权限:
private PermissionHelper permissionHelper; permissionHelper =new PermissionHelper(PicActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},100);
permissionHelper.request(new PermissionHelper.PermissionCallback() {
@Override
public void onPermissionGranted() {
}
@Override
public void onIndividualPermissionGranted(String[] grantedPermission) {
}
@Override
public void onPermissionDenied() {
}
@Override
public void onPermissionDeniedBySystem() {
}@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (permissionHelper!=null){
permissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}