1汇四、添加權(quán)限先锯玛,因?yàn)橐?qǐng)求網(wǎng)絡(luò)咐柜,并且存到本地,所以添加以下權(quán)限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
2攘残、布局activity_cache_bit_map.xml代碼,主要放一個(gè)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="加載網(wǎng)絡(luò)圖片并緩存"
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當(dāng)做文件名,并進(jìn)行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;
}
/**
* 從網(wǎng)絡(luò)獲取圖片后,保存至本地緩存
*
* @param url
* @param bitmap
*/
public void setBitmapToLocal(String url, Bitmap bitmap) {
try {
String fileName = url;//把圖片的url當(dāng)做文件名,并進(jìn)行MD5加密
File file = new File(getDiskCachePath(mContext) + "/file/" + fileName);//文件保存路徑
//通過(guò)得到文件的父文件,判斷父文件是否存在
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;
/**
*請(qǐng)求網(wǎng)絡(luò)圖片
* 作者:created by fanHongJiao
*/
public class NetCacheUtils {
private LocalCacheUtils mLocalCacheUtils;
static
{//輔助跳過(guò)證書
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() {
}
/**
* 從網(wǎng)絡(luò)下載圖片
*
* @param ivPic 顯示圖片的imageview
* @param url 下載圖片的網(wǎng)絡(luò)地址
*/
public void getBitmapFromNet(ImageView ivPic, String url) {
new BitmapTask().execute(ivPic, url);//啟動(dòng)AsyncTask
}
/**
* AsyncTask就是對(duì)handler和線程池的封裝
* 第一個(gè)泛型:參數(shù)類型
* 第二個(gè)泛型:更新進(jìn)度的泛型
* 第三個(gè)泛型:onPostExecute的返回結(jié)果
*/
class BitmapTask extends AsyncTask<Object, Void, Bitmap> {
private ImageView ivPic;
private String url;
/**
* 后臺(tái)耗時(shí)操作,存在于子線程中
*
* @param params
* @return
*/
@Override
protected Bitmap doInBackground(Object[] params) {
ivPic = (ImageView) params[0];
url = (String) params[1];
return getURLimage(url);
}
/**
* 更新進(jìn)度,在主線程中
*
* @param values
*/
@Override
protected void onProgressUpdate(Void[] values) {
super.onProgressUpdate(values);
}
/**
* 耗時(shí)方法結(jié)束后執(zhí)行該方法,主線程中
*
* @param result
*/
@Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
ivPic.setImageBitmap(result);
System.out.println("從網(wǎng)絡(luò)緩存圖片啦.....");
//從網(wǎng)絡(luò)獲取圖片后,保存至本地緩存
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);//設(shè)置超時(shí)
conn.setDoInput(true);
conn.setUseCaches(false);//不緩存
conn.connect();
InputStream is = conn.getInputStream();//獲得圖片的數(shù)據(jù)流
bmp = BitmapFactory.decodeStream(is);//讀取圖像數(shù)據(jù)
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;
}
//網(wǎng)絡(luò)加載圖片,在沒有緩存的情況下去請(qǐng)求網(wǎng)絡(luò)圖片泰涂,并將圖片保存在本地文件夾
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;
/**
* 網(wǎng)絡(luò)圖片緩存demo
* 加載網(wǎng)絡(luò)圖片,每次進(jìn)來(lái)先加載網(wǎng)絡(luò)圖片逼蒙,并且緩存圖片到本地从绘;
* 如果沒有網(wǎng)絡(luò)或者加載網(wǎng)絡(luò)圖片不成功,就從本地加載緩存的圖片
*/
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加載圖片,用網(wǎng)絡(luò)圖片的url加載圖片
// ivImage.setImageBitmap((Bitmap)msg.obj);
}
}
};
}
效果圖如下:
完結(jié)是牢。