1、添加权限先,因为要请求网络,并且存到本地,所以添加以下权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
2、布局activity_cache_bit_map.xml代码,主要放一个imageView用于放图片,如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center"
android:gravity="center"
tools:context="cacheBitmapDemo.CacheBitMapActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="加载网络图片并缓存"
android:id="@+id/btn_load_img"/>
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_marginTop="30dp"
android:id="@+id/iv_img"/>
</LinearLayout>
3、添加CacheImageBean.java类,代码如下:
package cacheBitmapDemo;
import android.graphics.Bitmap;
import android.widget.ImageView;
/**
*
* 作者:created by fanHongJiao
*/
public class CacheImageBean {
public Bitmap bitmapFile;
public ImageView gridImage;
public Bitmap getBitmapFile() {
return bitmapFile;
}
public void setBitmapFile(Bitmap bitmapFile) {
this.bitmapFile = bitmapFile;
}
public ImageView getGridImage() {
return gridImage;
}
public void setGridImage(ImageView gridImage) {
this.gridImage = gridImage;
}
public CacheImageBean() {
}
}
4、添加工具类LocalCacheUtils.java,代码如下:
package cacheBitmapDemo;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
* 作者:created by fanHongJiao
* 本地缓存
*/
public class LocalCacheUtils {
private static final String CACHE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/WerbNews";
private Context mContext;
public LocalCacheUtils(Context context) {
this.mContext = context;
}
public String getDiskCachePath(Context context) {
String cachePath = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
cachePath = context.getExternalCacheDir().getAbsolutePath();
} else {
cachePath = context.getCacheDir().getAbsolutePath();
}
return cachePath;
}
/**
* 从本地读取图片
*
* @param url
*/
public Bitmap getBitmapFromLocal(String url) {
String fileName = null;//把图片的url当做文件名,并进行MD5加密
try {
fileName = url;
File file = new File(getDiskCachePath(mContext) + "/file/" + fileName);//文件保存路径
Bitmap bitmap = null;
bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
if (!bitmap.equals(null)) {
return bitmap;
}
return null;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 从网络获取图片后,保存至本地缓存
*
* @param url
* @param bitmap
*/
public void setBitmapToLocal(String url, Bitmap bitmap) {
try {
String fileName = url;//把图片的url当做文件名,并进行MD5加密
File file = new File(getDiskCachePath(mContext) + "/file/" + fileName);//文件保存路径
//通过得到文件的父文件,判断父文件是否存在
File parentFile = file.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
//把图片保存至本地
bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
}
}
}
5、添加工具类NetCacheUtils,代码如下:
package cacheBitmapDemo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
*请求网络图片
* 作者:created by fanHongJiao
*/
public class NetCacheUtils {
private LocalCacheUtils mLocalCacheUtils;
static
{//辅助跳过证书
try
{
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier
(
new HostnameVerifier()
{
public boolean verify(String urlHostName, SSLSession session)
{
return true;
}
}
);
} catch (Exception e) {}
}
public NetCacheUtils(LocalCacheUtils localCacheUtils) {
mLocalCacheUtils = localCacheUtils;
}
public NetCacheUtils() {
}
/**
* 从网络下载图片
*
* @param ivPic 显示图片的imageview
* @param url 下载图片的网络地址
*/
public void getBitmapFromNet(ImageView ivPic, String url) {
new BitmapTask().execute(ivPic, url);//启动AsyncTask
}
/**
* AsyncTask就是对handler和线程池的封装
* 第一个泛型:参数类型
* 第二个泛型:更新进度的泛型
* 第三个泛型:onPostExecute的返回结果
*/
class BitmapTask extends AsyncTask<Object, Void, Bitmap> {
private ImageView ivPic;
private String url;
/**
* 后台耗时操作,存在于子线程中
*
* @param params
* @return
*/
@Override
protected Bitmap doInBackground(Object[] params) {
ivPic = (ImageView) params[0];
url = (String) params[1];
return getURLimage(url);
}
/**
* 更新进度,在主线程中
*
* @param values
*/
@Override
protected void onProgressUpdate(Void[] values) {
super.onProgressUpdate(values);
}
/**
* 耗时方法结束后执行该方法,主线程中
*
* @param result
*/
@Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
ivPic.setImageBitmap(result);
System.out.println("从网络缓存图片啦.....");
//从网络获取图片后,保存至本地缓存
mLocalCacheUtils.setBitmapToLocal(url, result);
}
}
}
//加载图片
public Bitmap getURLimage(String url) {
Bitmap bmp = null;
try {
URL myurl = new URL(url);
// 获得连接
HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();
conn.setConnectTimeout(60000);//设置超时
conn.setDoInput(true);
conn.setUseCaches(false);//不缓存
conn.connect();
InputStream is = conn.getInputStream();//获得图片的数据流
bmp = BitmapFactory.decodeStream(is);//读取图像数据
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return bmp;
}
private static void trustAllHttpsCertificates() throws NoSuchAlgorithmException, KeyManagementException
{
TrustManager[] trustAllCerts = new TrustManager[1];
trustAllCerts[0] = new TrustAllManager();
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(
sc.getSocketFactory());
}
private static class TrustAllManager implements X509TrustManager
{
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
public void checkServerTrusted(X509Certificate[] certs,
String authType)
throws CertificateException {
}
public void checkClientTrusted(X509Certificate[] certs,
String authType)
throws CertificateException {
}
}
}
6、添加工具类MyBitmapUtils类,代码如下:
package cacheBitmapDemo;
import android.content.Context;
import android.graphics.Bitmap;
import android.widget.ImageView;
/**
* 自定义图片加载工具
* 作者:created by fanHongJiao
*/
public class MyBitmapUtils {
private NetCacheUtils mNetCacheUtils;
private LocalCacheUtils mLocalCacheUtils;
private Context mContext;
public MyBitmapUtils(Context context) {
this.mContext = context;
mLocalCacheUtils = new LocalCacheUtils(context);
mNetCacheUtils = new NetCacheUtils(mLocalCacheUtils);
}
/**
* @param ivPic imageView
* @param url 图片地址
* @return
*/
public Bitmap disPlay(ImageView ivPic, String url) {
//本地缓存
Bitmap bitmap = mLocalCacheUtils.getBitmapFromLocal(url);
if (bitmap != null) {
return bitmap;
}
//网络加载图片,在没有缓存的情况下去请求网络图片,并将图片保存在本地文件夹
mNetCacheUtils.getBitmapFromNet(ivPic, url);
return bitmap;
}
}
7、CacheBitMapActivity代码如下:
package cacheBitmapDemo;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.example.viewpaerdemo.R;
import java.net.URL;
/**
* 网络图片缓存demo
* 加载网络图片,每次进来先加载网络图片,并且缓存图片到本地;
* 如果没有网络或者加载网络图片不成功,就从本地加载缓存的图片
*/
public class CacheBitMapActivity extends AppCompatActivity implements View.OnClickListener {
Button btnLoadImg;
ImageView ivImg;
private MyBitmapUtils myBitmapUtils;
private String imagUrl="https://i.625u.com/d/img/52353547.jpg";//图片的url
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cache_bit_map);
initView();
}
private void initView() {
btnLoadImg = findViewById(R.id.btn_load_img);
btnLoadImg.setOnClickListener(this);
ivImg = findViewById(R.id.iv_img);
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.btn_load_img) {
myBitmapUtils = new MyBitmapUtils(this);
Bitmap imageFile = myBitmapUtils.disPlay(ivImg, imagUrl);
CacheImageBean imageGrid = new CacheImageBean();
imageGrid.setBitmapFile(imageFile);
imageGrid.setGridImage(ivImg);
Message msg = Message.obtain();
msg.obj = imageGrid;
msg.what = 100;
handler.sendMessage(msg);
}
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 100:
CacheImageBean obj = (CacheImageBean) msg.obj;
obj.getGridImage().setImageBitmap(obj.getBitmapFile());
//Glide加载图片,直接加载本地图片所在文件
// Glide.with(mContext).load((Bitmap)obj.getBitmapFile()).into(obj.getGridImage());
//Glide加载图片,用网络图片的url加载图片
// ivImage.setImageBitmap((Bitmap)msg.obj);
}
}
};
}
效果图如下:
完结。