1.使用HttpHttpUrlConnection下载图片
首先在创建好Activity,完成xmlw文件,在AndroidManifest中加入访问网络权限,和访问储存文件的权限。
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
在Activity中设置好控件的绑定和监听事件,6.0以上在Activity中设置动态权限的加载:
package com.example.practice;
import android.Manifest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import com.master.permissionhelper.PermissionHelper;
public class DonActivity extends AppCompatActivity implements View.OnClickListener{
private Button button;
private SeekBar bar;
private ImageView imageView;
private String TAG = "HelloActivity";
private PermissionHelper permissionHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_don);
BlindID();
permissionHelper = new PermissionHelper(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
}
private void BlindID() {
button=findViewById(R.id.btn0);
imageView=findViewById(R.id.imageview);
bar=findViewById(R.id.bar);
button.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn0:
button.setEnabled(false);
permissionHelper.request(new PermissionHelper.PermissionCallback(){
@Override
public void onPermissionGranted() {
Log.e(TAG,"onPermissionGranted...");
DownloadTask downloadTa=new DownloadTask(DonActivity.this,imageView,button);
downloadTa.execute("http://img31.mtime.cn/mg/2012/10/30/201631.37192876.jpg","wangz.jpg");
}
@Override
public void onIndividualPermissionGranted(String[] grantedPermission) {
Log.e(TAG,"onIndividualPermissionGranted...");
}
@Override
public void onPermissionDenied() {
Log.e(TAG,"onPermissionDenied...");
}
@Override
public void onPermissionDeniedBySystem() {
Log.e(TAG,"onPermissionDeniedBySystem...");
}
});
break;
}
}
}
创建一个Download类继承AsyncTask,并重写AsyncTask。创建构造函数用来传送Activity的控件参数。
public class DownloadTask extends AsyncTask<String,Integer,Integer> {
private Context context;
private Button btn;
private ImageView imageView;
public DownloadTask(Context context,ImageView mimageView,Button downloadBtn){
this.context=context;
this.imageView=mimageView;
this.btn=downloadBtn;
}
再在doInBackground()里进行耗时的下载操作;定义输入流和输出流,创建好下载的文件目录,
所以我们先需要判断文件是否存在;如果文件存在返回一个值给onPostExecute方法,让其进行存在操作。
如果不存在创建文件目录,和文件。(这里需要用到下面的判断文件是否存在,和创建文件目录以及文件方法)
创建URl获取下载地址,发送HttpURLConnection请求,使用if来判断请求是否成功;
将下载流放置输入流中,创建一个缓存区,再由缓存区写入文件。
这里用定义lenth来判断是否把下载的文件下载完成,如果完成会给lenth一个-1 的值,所以只要lenth不为-1,继续进行传输下载
protected Integer doInBackground(String... strings) {
InputStream inputStream=null;
OutputStream outputStream=null;
File file = null;
fileName=path+strings[1];
if (isFileExists(fileName)){
return 1;
}
try {
URL url=new URL(strings[0]);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
if (httpURLConnection.getResponseCode()==200) {
inputStream = httpURLConnection.getInputStream();
}
createDir(path);
file = createFile(path+strings[1]);
outputStream=new FileOutputStream(file);
byte buffer[]=new byte[4*1024];
int length=0;
int sum=0;
while ((length=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,length);
sum+=length;
publishProgress(0,sum);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
工具方法
/**
* 工具方法——判断文件已存在
*
* @return
*/
private boolean isFileExists(String sDpath) {
File file = new File(sDpath);
if (file.exists()) {
return true;
}
return false;
}
/**
* 工具方法——创建目录
*/
private boolean createDir(String dirName) {
File file = new File(dirName);
boolean isCreateDir = file.mkdir();
return isCreateDir;
}
/**
* 工具方法——创建文件
* @param
*/
private File createFile(String fileName) {
File file = new File(fileName);
boolean isCreateFile = false;
try {
isCreateFile = file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
再由doInBackground方法所返回的值,来判断主线程所需要做的操作:
如果返回的值为1,向用户显示文件存在
如果返回为0,将图片加载到界面上。
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
switch (integer){
case 1:
Toast.makeText(context,"文件已存在",Toast.LENGTH_SHORT).show();
btn.setEnabled(true);
break;
case 0:
btn.setEnabled(true);
Bitmap bitmap=BitmapFactory.decodeFile(fileName);
imageView.setImageBitmap(bitmap);
break;