Browse Source

first commit

u269069 5 years ago
commit
b7eab3eb86
6 changed files with 427 additions and 0 deletions
  1. 142 0
      AsyncImageLoader.java
  2. 41 0
      FileCache.java
  3. 110 0
      ImageUtil.java
  4. 43 0
      MemoryCache.java
  5. 91 0
      OssUpload.java
  6. 0 0
      README.md

+ 142 - 0
AsyncImageLoader.java

@@ -0,0 +1,142 @@
+package com.easemob.easeui.oss;
+
+import android.app.Activity;
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.widget.ImageView;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.WeakHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+public class AsyncImageLoader {
+
+	  private MemoryCache mMemoryCache;
+	  private FileCache mFileCache;
+	  private ExecutorService mExecutorService;
+      private Context context;
+	  private Map<ImageView, String> mImageViews = Collections
+	      .synchronizedMap(new WeakHashMap<ImageView, String>());
+
+	  private List<LoadPhotoTask> mTaskQueue = new ArrayList<LoadPhotoTask>();
+
+	  public AsyncImageLoader(Context context, MemoryCache memoryCache, FileCache fileCache) {
+		  this.context = context;
+	    mMemoryCache = memoryCache;
+	    mFileCache = fileCache;
+	    mExecutorService = Executors.newFixedThreadPool(5);
+	  }
+
+	  public Bitmap loadBitmap(ImageView imageView, String url) {
+
+	    mImageViews.put(imageView, url);
+	    Bitmap bitmap = mMemoryCache.get(url);
+	    if(bitmap == null) {
+	      enquequeLoadPhoto(url, imageView);
+	    }
+	    return bitmap;
+	  }
+
+	  private void enquequeLoadPhoto(String url, ImageView imageView) {
+	    if(isTaskExisted(url))
+	      return;
+	    LoadPhotoTask task = new LoadPhotoTask(url, imageView);
+	    synchronized (mTaskQueue) {
+	      mTaskQueue.add(task);
+	    }
+	    mExecutorService.execute(task);
+	  }
+
+	  private boolean isTaskExisted(String url) {
+	    if(url == null)
+	      return false;
+	    synchronized (mTaskQueue) {
+	      int size = mTaskQueue.size();
+	      for(int i=0; i<size; i++) {
+	        LoadPhotoTask task = mTaskQueue.get(i);
+	        if(task != null && task.getUrl().equals(url))
+	          return true;
+	      }
+	    }
+	    return false;
+	  }
+
+	  private Bitmap getBitmapByUrl(String url) {
+	    File f = mFileCache.getFile(url);
+	    Bitmap b = ImageUtil.decodeFile(f);
+	    if (b != null)
+	      return b;
+	    return ImageUtil.loadBitmapFromWeb(context,url, f);
+	  }
+
+	  private boolean imageViewReused(ImageView imageView, String url) {
+	    String tag = mImageViews.get(imageView);
+	    if (tag == null || !tag.equals(url))
+	      return true;
+	    return false;
+	  }
+	  private void removeTask(LoadPhotoTask task) {
+	    synchronized (mTaskQueue) {
+	      mTaskQueue.remove(task);
+	    }
+	  }
+	  class LoadPhotoTask implements Runnable {
+	    private String url;
+	    private ImageView imageView;  
+	    LoadPhotoTask(String url, ImageView imageView) {
+	      this.url = url;
+	      this.imageView = imageView;
+	    }
+	    @Override
+	    public void run() {
+	      if (imageViewReused(imageView, url)) {
+	        removeTask(this);
+	        return;
+	      }
+	      Bitmap bmp = getBitmapByUrl(url);
+	      mMemoryCache.put(url, bmp);
+	      if (!imageViewReused(imageView, url)) {
+	      BitmapDisplayer bd = new BitmapDisplayer(bmp, imageView, url);
+	      Activity a = (Activity) imageView.getContext();
+	      a.runOnUiThread(bd);
+	      }
+	      removeTask(this);
+	    }
+	    public String getUrl() {
+	      return url;
+	    }
+	  }
+
+	  class BitmapDisplayer implements Runnable {
+	    private Bitmap bitmap;
+	    private ImageView imageView;
+	    private String url;
+	    public BitmapDisplayer(Bitmap b, ImageView imageView, String url) {
+	      bitmap = b;
+	      this.imageView = imageView;
+	      this.url = url;
+	    }
+	    public void run() {
+	      if (imageViewReused(imageView, url))
+	        return;
+	      if (bitmap != null)
+	        imageView.setImageBitmap(bitmap);
+	    }
+	  }
+
+	  public void destroy() {
+	    mMemoryCache.clear();
+	    mMemoryCache = null;
+	    mImageViews.clear();
+	    mImageViews = null;
+	    mTaskQueue.clear();
+	    mTaskQueue = null;
+	    mExecutorService.shutdown();
+	    mExecutorService = null;
+	  }
+}

+ 41 - 0
FileCache.java

@@ -0,0 +1,41 @@
+package com.easemob.easeui.oss;
+
+import android.content.Context;
+
+import java.io.File;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+
+public class FileCache {
+
+	  //�����ļ�Ŀ¼ 
+	  private File mCacheDir;
+	  /**
+	   * ���������ļ�Ŀ¼�������SD������ʹ��SD�����û����ʹ��ϵͳ�Դ��Ŀ¼
+	   * @param context
+	   * @param cacheDir ͼƬ�����һ��Ŀ¼
+	   */
+	public FileCache(Context context, File cacheDir, String dir){
+	if(android.os.Environment.getExternalStorageState()
+			.equals(android.os.Environment.MEDIA_MOUNTED))
+	      mCacheDir = new File(cacheDir, dir);
+	   else
+	    mCacheDir = context.getCacheDir();// ��λ�ȡϵͳ���õĻ���洢·��
+	   if(!mCacheDir.exists()) mCacheDir.mkdirs();
+	  }
+	  public File getFile(String url){
+	    File f=null;
+	    try {
+	//��url���б༭���������·������
+	      String filename = URLEncoder.encode(url,"utf-8");
+	      f = new File(mCacheDir, filename);
+	    } catch (UnsupportedEncodingException e) {
+	      e.printStackTrace();
+	    }
+	    return f;
+	  }
+	  public void clear(){//�����ļ�
+	    File[] files = mCacheDir.listFiles();
+	    for(File f:files)f.delete();
+	}
+}

+ 110 - 0
ImageUtil.java

@@ -0,0 +1,110 @@
+package com.easemob.easeui.oss;
+
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.util.Log;
+
+import com.alibaba.sdk.android.oss.ClientConfiguration;
+import com.alibaba.sdk.android.oss.ClientException;
+import com.alibaba.sdk.android.oss.OSS;
+import com.alibaba.sdk.android.oss.OSSClient;
+import com.alibaba.sdk.android.oss.ServiceException;
+import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
+import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
+import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
+import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
+import com.alibaba.sdk.android.oss.model.GetObjectRequest;
+import com.alibaba.sdk.android.oss.model.GetObjectResult;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+
+public class ImageUtil {
+
+	static String endpoint = "http://img.lesgoapp.cc";
+	private static String name = "lesgo";
+	static  Bitmap bitmap = null;
+	static  InputStream inputStream  = null;
+	static  OutputStream os = null;
+
+	  public static Bitmap loadBitmapFromWeb(Context context,String url, final File file) {
+
+	    try {
+			OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider("LTAIvkmoS1lN2mCd", "3KLqFPW20hpkXUmFvBwY70P5sxiDcG");
+			ClientConfiguration conf = new ClientConfiguration();
+			conf.setConnectionTimeout(15 * 1000); // 连接超时,默认15秒
+			conf.setSocketTimeout(15 * 1000); // socket超时,默认15秒
+			conf.setMaxConcurrentRequest(5); // 最大并发请求书,默认5个
+			conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次
+			OSS oss = new OSSClient(context, endpoint, credentialProvider, conf);
+			GetObjectRequest get = new GetObjectRequest(name, url);
+			OSSAsyncTask task = oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
+				@Override
+				public void onSuccess(GetObjectRequest request, GetObjectResult result) {
+					// 请求成功
+					 inputStream = result.getObjectContent();
+					try {
+						os = new FileOutputStream(file);
+						copyStream(inputStream, os);//
+						bitmap = decodeFile(file);
+					} catch (FileNotFoundException e) {
+						e.printStackTrace();
+					}
+				}
+
+				@Override
+				public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
+					// 请求异常
+					if (clientExcepion != null) {
+						// 本地异常如网络异常等
+						clientExcepion.printStackTrace();
+					}
+					if (serviceException != null) {
+						// 服务异常
+						Log.e("ErrorCode", serviceException.getErrorCode());
+						Log.e("RequestId", serviceException.getRequestId());
+						Log.e("HostId", serviceException.getHostId());
+						Log.e("RawMessage", serviceException.getRawMessage());
+					}
+				}
+			});
+	      return bitmap;
+	    } catch (Exception ex) {
+	      ex.printStackTrace();
+	      return null;
+	    } finally {
+	      try {
+	        if(os != null) os.close();
+	        if(inputStream != null) inputStream.close();
+	      } catch (IOException e) {  }
+	    }
+	  }
+	  public static Bitmap decodeFile(File f) {
+	    try {
+	      return BitmapFactory.decodeStream(new FileInputStream(f), null, null);
+	    } catch (Exception e) { } 
+	    return null;
+	  }
+	  private static void copyStream(InputStream is, OutputStream os) {
+	    final int buffer_size = 1024;
+	    try {
+	      byte[] bytes = new byte[buffer_size];
+	      for (;;) {
+	        int count = is.read(bytes, 0, buffer_size);
+	        if (count == -1)
+	          break;
+	        os.write(bytes, 0, count);
+	      }
+	    } catch (Exception ex) {
+	      ex.printStackTrace();
+	    }
+	  }
+}

+ 43 - 0
MemoryCache.java

@@ -0,0 +1,43 @@
+package com.easemob.easeui.oss;
+
+import android.graphics.Bitmap;
+
+import java.lang.ref.SoftReference;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+public class MemoryCache {
+	// ���Ļ����� 
+	private static final int MAX_CACHE_CAPACITY = 30;
+	private HashMap<String, SoftReference<Bitmap>> mCacheMap =
+			new LinkedHashMap<String, SoftReference<Bitmap>>() {
+		private static final long serialVersionUID = 1L;
+		protected boolean removeEldestEntry(
+				Entry<String,SoftReference<Bitmap>> eldest){
+			return size() > MAX_CACHE_CAPACITY;};
+	};
+
+	public Bitmap get(String id){
+		if(!mCacheMap.containsKey(id)) return null;
+		SoftReference<Bitmap> ref = mCacheMap.get(id);
+		return ref.get();
+	}
+	public void put(String id, Bitmap bitmap){
+		mCacheMap.put(id, new SoftReference<Bitmap>(bitmap));
+	}
+	public void clear() {
+		try {
+			for(Map.Entry<String,SoftReference<Bitmap>>entry
+					:mCacheMap.entrySet()) 
+			{  SoftReference<Bitmap> sr = entry.getValue();
+			if(null != sr) {
+				Bitmap bmp = sr.get();
+				if(null != bmp) bmp.recycle();
+			}
+			}
+			mCacheMap.clear();
+		} catch (Exception e) {
+			e.printStackTrace();}
+	}
+}

+ 91 - 0
OssUpload.java

@@ -0,0 +1,91 @@
+package com.easemob.easeui.oss;
+
+import android.content.Context;
+import android.util.Log;
+
+import com.alibaba.sdk.android.oss.ClientConfiguration;
+import com.alibaba.sdk.android.oss.ClientException;
+import com.alibaba.sdk.android.oss.OSS;
+import com.alibaba.sdk.android.oss.OSSClient;
+import com.alibaba.sdk.android.oss.ServiceException;
+import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
+import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
+import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
+import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
+import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
+import com.alibaba.sdk.android.oss.model.PutObjectRequest;
+import com.alibaba.sdk.android.oss.model.PutObjectResult;
+
+/**
+ * Created by 程鑫磊 on 2016/11/17.
+ * on 2016/11/17.
+ */
+public class OssUpload {
+
+    OnResponseListener onResponseListener;
+
+    public void setOnResponseListener(OnResponseListener onResponseListener) {
+        this.onResponseListener = onResponseListener;
+    }
+
+    public void ossUpload(Context context, final String path,String name){
+        String endpoint = "http://img.lesgoapp.cc";
+// 明文设置secret的方式建议只在测试时使用,更多鉴权模式请参考后面的`访问控制`章节
+        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider("LTAIvkmoS1lN2mCd", "3KLqFPW20hpkXUmFvBwY70P5sxiDcG");
+        ClientConfiguration conf = new ClientConfiguration();
+        conf.setConnectionTimeout(25 * 1000); // 连接超时,默认15秒
+        conf.setSocketTimeout(60 * 1000); // socket超时,默认15秒
+        conf.setMaxConcurrentRequest(9); // 最大并发请求书,默认5个
+        conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次
+        OSS oss = new OSSClient(context, endpoint, credentialProvider, conf);
+        // 构造上传请求
+        PutObjectRequest put = new PutObjectRequest("lesgo", name, path);
+
+// 异步上传时可以设置进度回调
+        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
+            @Override
+            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
+                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
+            }
+        });
+
+        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
+            @Override
+            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
+                Log.d("PutObject", "UploadSuccess");
+                Log.d("ETag", result.getETag());
+                Log.d("RequestId", result.getRequestId());
+                if(onResponseListener != null){
+                   onResponseListener.sussce(path);
+                }
+            }
+
+            @Override
+            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
+                // 请求异常
+                if (clientExcepion != null) {
+                    // 本地异常如网络异常等
+                    clientExcepion.printStackTrace();
+                    if(onResponseListener != null){
+                        onResponseListener.sussce("本地异常");
+                    }
+                }
+                if (serviceException != null) {
+                    // 服务异常
+                    Log.e("ErrorCode", serviceException.getErrorCode());
+                    Log.e("RequestId", serviceException.getRequestId());
+                    Log.e("HostId", serviceException.getHostId());
+                    Log.e("RawMessage", serviceException.getRawMessage());
+                    if(onResponseListener != null){
+                        onResponseListener.sussce("服务异常");
+                    }
+                }
+                }
+        });
+    }
+
+    public interface OnResponseListener{
+        public void sussce(Object obj);
+        public void error(Object... obj);
+    }
+}

+ 0 - 0
README.md