布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:onClick="download"
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下载图片"
android:layout_centerHorizontal="true"/>
<ImageView
android:id="@+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@id/button"/>
</RelativeLayout>
MainActivity:
package com.example.zjday13_download_picture;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import com.example.zjday13_download_picture.utils.FileUtil;
import com.example.zjday13_download_picture.utils.MyTask;
public class MainActivity extends Activity {
private ImageView imageView;
String path ="https://www.baidu.com/img/bd_logo1.png";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=(ImageView) findViewById(R.id.image_view);
}
/**
* 下载图片
* @param v
*/
public void download(View v){
//先判断,如果SD卡有图片,直接加载否则开启异步任务下载图片
Bitmap bitmap =FileUtil.readImage(path);
if(bitmap!=null){
imageView.setImageBitmap(bitmap);
Log.i("info", "本地有图片,从本地加载");
}else{
new MyTask(getApplicationContext(),imageView).execute(path);
Log.i("info", "从网络下载图片");
}
}
}
文件的工具类:
package com.example.zjday13_download_picture.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
public class FileUtil {
//保存图片的缓存路径
//Environment.getExternalStorageDirectory() 得到sd卡的根目录
private static final String PATH=Environment.getExternalStorageDirectory()
+"/downloadpicture/images";
public static boolean isMountend(){
//获取sd卡的状态
String state =Environment.getExternalStorageState();
return state.equals(Environment.MEDIA_MOUNTED);
}
//从图片路径获取图片的名字
public static String getFileName(String url){
return url.substring(url.lastIndexOf("/")+1);
}
public static void saveImage(String url, byte[] buffer) throws IOException {
//1.判断sd卡状态,如果sd卡不可用,则直接返回
if(!isMountend()) return;
//2.判断当前缓存的目录是否存在
File dir=new File(PATH);
if(!dir.exists()){
dir.mkdirs();//级联创建
}
//3.将图片的字节数写到指定的文件中(需要知道文件的缓存目录和图图片的名字)
FileOutputStream fos=new FileOutputStream(new File(dir, getFileName(url)));
fos.write(buffer);
fos.close();
}
/**
* 根据传入的图片的路径,获取sd卡中缓存的图片
* @param path2
* @return
*/
public static Bitmap readImage(String url) {
if(!isMountend()) return null;
File imageFile =new File(PATH,getFileName(url));
if(imageFile.exists())
{
//把指定路径的文件转换成Bitmap格式
return BitmapFactory.decodeFile(imageFile.getAbsolutePath());
}
return null;
}
}
异步下载任务:
package com.example.zjday13_download_picture.utils;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import android.widget.Toast;
public class MyTask extends AsyncTask<String, Void, Bitmap> {
private Context context;
private ImageView imageView;
public MyTask(Context context,ImageView imageView) {
super();
this.context=context;
this.imageView = imageView;
}
@Override
protected Bitmap doInBackground(String... params) {
String path =params[0];
try {
URL url =new URL(path);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
if(conn.getResponseCode()==200){
InputStream inStream=conn.getInputStream();
ByteArrayOutputStream baso=new ByteArrayOutputStream();
int len =0;
byte[]buffer=new byte[1024];
while((len =inStream.read(buffer))!=-1){
baso.write(buffer, 0, len);
}
buffer =baso.toByteArray();
//将获取的数据写入Sd卡中
FileUtil.saveImage(path,buffer);
Bitmap bitmap=BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
return bitmap;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if(result!=null){
imageView.setImageBitmap(result);
Toast.makeText(context, "加载。。。。", Toast.LENGTH_LONG).show();
}
}
}