1.新建 :SmartImageDemo\app\src\main\res\xml\network_security_config.xml
该配置用于HTTP请求
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
2.AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.glsite.smartimagedemo">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:networkSecurityConfig="@xml/network_security_config">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
3.activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context=".MainActivity">
<com.glsite.smartimagedemo.loopj.android.image.SmartImageView
android:id="@+id/siv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
4.第三方控件
4.1
BitmapImage.java
package com.glsite.smartimagedemo.loopj.android.image;
import android.content.Context;
import android.graphics.Bitmap;
public class BitmapImage implements SmartImage {
private Bitmap bitmap;
public BitmapImage(Bitmap bitmap) {
this.bitmap = bitmap;
}
public Bitmap getBitmap(Context context) {
return bitmap;
}
}
4.2
ContactImage.java
package com.glsite.smartimagedemo.loopj.android.image;
import java.io.InputStream;
import android.content.ContentUris;
import android.content.ContentResolver;
import android.content.Context;
import android.provider.ContactsContract;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
public class ContactImage implements SmartImage {
private long contactId;
public ContactImage(long contactId) {
this.contactId = contactId;
}
public Bitmap getBitmap(Context context) {
Bitmap bitmap = null;
ContentResolver contentResolver = context.getContentResolver();
try {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, uri);
if(input != null) {
bitmap = BitmapFactory.decodeStream(input);
}
} catch(Exception e) {
e.printStackTrace();
}
return bitmap;
}
}
4.3
SmartImage.java
package com.glsite.smartimagedemo.loopj.android.image;
import java.io.InputStream;
import android.content.ContentUris;
import android.content.ContentResolver;
import android.content.Context;
import android.provider.ContactsContract;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
public class ContactImage implements SmartImage {
private long contactId;
public ContactImage(long contactId) {
this.contactId = contactId;
}
public Bitmap getBitmap(Context context) {
Bitmap bitmap = null;
ContentResolver contentResolver = context.getContentResolver();
try {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(contentResolver, uri);
if(input != null) {
bitmap = BitmapFactory.decodeStream(input);
}
} catch(Exception e) {
e.printStackTrace();
}
return bitmap;
}
}
4.4
SmartImageTask.java
package com.glsite.smartimagedemo.loopj.android.image;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
public class SmartImageTask implements Runnable {
private static final int BITMAP_READY = 0;
private boolean cancelled = false;
private OnCompleteHandler onCompleteHandler;
private SmartImage image;
private Context context;
public static class OnCompleteHandler extends Handler {
@Override
public void handleMessage(Message msg) {
Bitmap bitmap = (Bitmap)msg.obj;
onComplete(bitmap);
}
public void onComplete(Bitmap bitmap){};
}
public abstract static class OnCompleteListener {
public abstract void onComplete();
}
public SmartImageTask(Context context, SmartImage image) {
this.image = image;
this.context = context;
}
@Override
public void run() {
if(image != null) {
complete(image.getBitmap(context));
context = null;
}
}
public void setOnCompleteHandler(OnCompleteHandler handler){
this.onCompleteHandler = handler;
}
public void cancel() {
cancelled = true;
}
public void complete(Bitmap bitmap){
if(onCompleteHandler != null && !cancelled) {
onCompleteHandler.sendMessage(onCompleteHandler.obtainMessage(BITMAP_READY, bitmap));
}
}
}
4.5
SmartImageView.java
package com.glsite.smartimagedemo.loopj.android.image;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.widget.ImageView;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SmartImageView extends ImageView {
private static final int LOADING_THREADS = 4;
private static ExecutorService threadPool = Executors.newFixedThreadPool(LOADING_THREADS);
private SmartImageTask currentTask;
public SmartImageView(Context context) {
super(context);
}
public SmartImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SmartImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
// Helpers to set image by URL
public void setImageUrl(String url) {
setImage(new WebImage(url));
}
public void setImageUrl(String url, SmartImageTask.OnCompleteListener completeListener) {
setImage(new WebImage(url), completeListener);
}
public void setImageUrl(String url, final Integer fallbackResource) {
setImage(new WebImage(url), fallbackResource);
}
public void setImageUrl(String url, final Integer fallbackResource, SmartImageTask.OnCompleteListener completeListener) {
setImage(new WebImage(url), fallbackResource, completeListener);
}
public void setImageUrl(String url, final Integer fallbackResource, final Integer loadingResource) {
setImage(new WebImage(url), fallbackResource, loadingResource);
}
public void setImageUrl(String url, final Integer fallbackResource, final Integer loadingResource, SmartImageTask.OnCompleteListener completeListener) {
setImage(new WebImage(url), fallbackResource, loadingResource, completeListener);
}
// Helpers to set image by contact address book id
public void setImageContact(long contactId) {
setImage(new ContactImage(contactId));
}
public void setImageContact(long contactId, final Integer fallbackResource) {
setImage(new ContactImage(contactId), fallbackResource);
}
public void setImageContact(long contactId, final Integer fallbackResource, final Integer loadingResource) {
setImage(new ContactImage(contactId), fallbackResource, fallbackResource);
}
// Set image using SmartImage object
public void setImage(final SmartImage image) {
setImage(image, null, null, null);
}
public void setImage(final SmartImage image, final SmartImageTask.OnCompleteListener completeListener) {
setImage(image, null, null, completeListener);
}
public void setImage(final SmartImage image, final Integer fallbackResource) {
setImage(image, fallbackResource, fallbackResource, null);
}
public void setImage(final SmartImage image, final Integer fallbackResource, SmartImageTask.OnCompleteListener completeListener) {
setImage(image, fallbackResource, fallbackResource, completeListener);
}
public void setImage(final SmartImage image, final Integer fallbackResource, final Integer loadingResource) {
setImage(image, fallbackResource, loadingResource, null);
}
public void setImage(final SmartImage image, final Integer fallbackResource, final Integer loadingResource, final SmartImageTask.OnCompleteListener completeListener) {
// Set a loading resource
if(loadingResource != null){
setImageResource(loadingResource);
}
// Cancel any existing tasks for this image view
if(currentTask != null) {
currentTask.cancel();
currentTask = null;
}
// Set up the new task
currentTask = new SmartImageTask(getContext(), image);
currentTask.setOnCompleteHandler(new SmartImageTask.OnCompleteHandler() {
@Override
public void onComplete(Bitmap bitmap) {
if(bitmap != null) {
setImageBitmap(bitmap);
} else {
// Set fallback resource
if(fallbackResource != null) {
setImageResource(fallbackResource);
}
}
if(completeListener != null){
completeListener.onComplete();
}
}
});
// Run the task in a threadpool
threadPool.execute(currentTask);
}
public static void cancelAllTasks() {
threadPool.shutdownNow();
threadPool = Executors.newFixedThreadPool(LOADING_THREADS);
}
}
4.6
WebImage.java
package com.glsite.smartimagedemo.loopj.android.image;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class WebImage implements SmartImage {
private static final int CONNECT_TIMEOUT = 5000;
private static final int READ_TIMEOUT = 10000;
private static WebImageCache webImageCache;
private String url;
public WebImage(String url) {
this.url = url;
}
public Bitmap getBitmap(Context context) {
// Don't leak context
if(webImageCache == null) {
webImageCache = new WebImageCache(context);
}
// Try getting bitmap from cache first
Bitmap bitmap = null;
if(url != null) {
bitmap = webImageCache.get(url);
if(bitmap == null) {
bitmap = getBitmapFromUrl(url);
if(bitmap != null){
webImageCache.put(url, bitmap);
}
}
}
return bitmap;
}
private Bitmap getBitmapFromUrl(String url) {
Bitmap bitmap = null;
try {
URLConnection conn = new URL(url).openConnection();
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(READ_TIMEOUT);
bitmap = BitmapFactory.decodeStream((InputStream) conn.getContent());
} catch(Exception e) {
e.printStackTrace();
}
return bitmap;
}
public static void removeFromCache(String url) {
if(webImageCache != null) {
webImageCache.remove(url);
}
}
}
4.7
WebImageCache.java
package com.glsite.smartimagedemo.loopj.android.image;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class WebImageCache {
private static final String DISK_CACHE_PATH = "/web_image_cache/";
private ConcurrentHashMap<String, SoftReference<Bitmap>> memoryCache;
private String diskCachePath;
private boolean diskCacheEnabled = false;
private ExecutorService writeThread;
public WebImageCache(Context context) {
// Set up in-memory cache store
memoryCache = new ConcurrentHashMap<String, SoftReference<Bitmap>>();
// Set up disk cache store
Context appContext = context.getApplicationContext();
diskCachePath = appContext.getCacheDir().getAbsolutePath() + DISK_CACHE_PATH;
File outFile = new File(diskCachePath);
outFile.mkdirs();
diskCacheEnabled = outFile.exists();
// Set up threadpool for image fetching tasks
writeThread = Executors.newSingleThreadExecutor();
}
public Bitmap get(final String url) {
Bitmap bitmap = null;
// Check for image in memory
bitmap = getBitmapFromMemory(url);
// Check for image on disk cache
if(bitmap == null) {
bitmap = getBitmapFromDisk(url);
// Write bitmap back into memory cache
if(bitmap != null) {
cacheBitmapToMemory(url, bitmap);
}
}
return bitmap;
}
public void put(String url, Bitmap bitmap) {
cacheBitmapToMemory(url, bitmap);
cacheBitmapToDisk(url, bitmap);
}
public void remove(String url) {
if(url == null){
return;
}
// Remove from memory cache
memoryCache.remove(getCacheKey(url));
// Remove from file cache
File f = new File(diskCachePath, getCacheKey(url));
if(f.exists() && f.isFile()) {
f.delete();
}
}
public void clear() {
// Remove everything from memory cache
memoryCache.clear();
// Remove everything from file cache
File cachedFileDir = new File(diskCachePath);
if(cachedFileDir.exists() && cachedFileDir.isDirectory()) {
File[] cachedFiles = cachedFileDir.listFiles();
for(File f : cachedFiles) {
if(f.exists() && f.isFile()) {
f.delete();
}
}
}
}
private void cacheBitmapToMemory(final String url, final Bitmap bitmap) {
memoryCache.put(getCacheKey(url), new SoftReference<Bitmap>(bitmap));
}
private void cacheBitmapToDisk(final String url, final Bitmap bitmap) {
writeThread.execute(new Runnable() {
@Override
public void run() {
if(diskCacheEnabled) {
BufferedOutputStream ostream = null;
try {
ostream = new BufferedOutputStream(new FileOutputStream(new File(diskCachePath, getCacheKey(url))), 2*1024);
bitmap.compress(CompressFormat.PNG, 100, ostream);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if(ostream != null) {
ostream.flush();
ostream.close();
}
} catch (IOException e) {}
}
}
}
});
}
private Bitmap getBitmapFromMemory(String url) {
Bitmap bitmap = null;
SoftReference<Bitmap> softRef = memoryCache.get(getCacheKey(url));
if(softRef != null){
bitmap = softRef.get();
}
return bitmap;
}
private Bitmap getBitmapFromDisk(String url) {
Bitmap bitmap = null;
if(diskCacheEnabled){
String filePath = getFilePath(url);
File file = new File(filePath);
if(file.exists()) {
bitmap = BitmapFactory.decodeFile(filePath);
}
}
return bitmap;
}
private String getFilePath(String url) {
return diskCachePath + getCacheKey(url);
}
private String getCacheKey(String url) {
if(url == null){
throw new RuntimeException("Null url passed in");
} else {
return url.replaceAll("[.:/,%?&=]", "+").replaceAll("[+]+", "+");
}
}
}
5.
MainActivity.java
package com.glsite.smartimagedemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.glsite.smartimagedemo.loopj.android.image.SmartImageView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SmartImageView siv = findViewById(R.id.siv);
siv.setImageUrl("http://192.168.1.1:8080/Day10/img/a.jpg", R.mipmap.ic_launcher);
}
}