轉自:http://blog.csdn.net/imzoer/article/details/9422013
在很多場景,作爲開發都會想到,在執行完畢一個任務的時候,能執行一個callback函數是多麼好的事情。
現在模擬一下這個情景:
定義三個類。分別是主函數類。callback函數的接口類。業務處理類。在業務處理類中,處理完業務之後,執行一個callback函數。
- package comz;
- public class Main {
- public static void main(String[] args) {
- new TestCallBack().compute(1000, new ComputeCallBack() {
- @Override
- public void onComputeEnd() {
- System.out.println("end back!!!");
- }
- });
- }
- }
這是主函數類。new了一個業務處理類來處理邏輯,並在處理完畢之後,執行callback函數。
- package comz;
- public class TestCallBack {
- public void compute(int n, ComputeCallBack callback) {
- for (int i = 0; i < n; i++) {
- System.out.println(i);
- }
- callback.onComputeEnd();
- }
- }
這是業務處理類。僅僅輸出一些數字,然後執行回調函數。
- package comz;
- public interface ComputeCallBack {
- public void onComputeEnd();
- }
這是回調函數的接口。
--------------------------------------
運行上面的代碼,就會在輸出結束的時候調用在Main裏面的callback函數,輸出System.out.println("end back!!!");
--------------------------------------
這裏的原理是:
在主類中,新建業務類的時候,傳遞進去的第二個參數是一個實現了回調接口的匿名類對象。
在業務類中,我們調用了這個對象的onComputeEnd方法。在執行onComputeEnd的時候,jvm會找到這個對象的函數實現並調用。於是就輸出了end back!!!
---------------------------------------
寫這篇文章的靈感來自於這裏
這篇文章介紹了安卓下,下載圖片並緩存。文章中亮點不僅僅是回調函數的使用,而且還使用了SoftReference來做內存緩存。
下面的代碼,用SoftReference寫入內存緩存:
- /**
- * 從網絡端下載圖片
- *
- * @param url
- * 網絡圖片的URL地址
- * @param cache2Memory
- * 是否緩存(緩存在內存中)
- * @return bitmap 圖片bitmap結構
- *
- */
- public Bitmap getBitmapFromUrl(String url, boolean cache2Memory) {
- Bitmap bitmap = null;
- try {
- URL u = new URL(url);
- HttpURLConnection conn = (HttpURLConnection) u.openConnection();
- InputStream is = conn.getInputStream();
- bitmap = BitmapFactory.decodeStream(is);
- if (cache2Memory) {
- // 1.緩存bitmap至內存軟引用中
- imageCache.put(url, new SoftReference<Bitmap>(bitmap));
- if (cache2FileFlag) {
- // 2.緩存bitmap至/data/data/packageName/cache/文件夾中
- String fileName = getMD5Str(url);
- String filePath = this.cachedDir + "/" + fileName;
- FileOutputStream fos = new FileOutputStream(filePath);
- bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
- }
- }
- is.close();
- conn.disconnect();
- return bitmap;
- } catch (IOException e) {
- e.printStackTrace();
- return null;
- }
- }
下面是從內存緩存中讀取圖片並返回:;
- /**
- * 從內存緩存中獲取bitmap
- *
- * @param url
- * @return bitmap or null.
- */
- public Bitmap getBitmapFromMemory(String url) {
- Bitmap bitmap = null;
- if (imageCache.containsKey(url)) {
- synchronized (imageCache) {
- SoftReference<Bitmap> bitmapRef = imageCache.get(url);
- if (bitmapRef != null) {
- bitmap = bitmapRef.get();
- return bitmap;
- }
- }
- }
- // 從外部緩存文件讀取
- if (cache2FileFlag) {
- bitmap = getBitmapFromFile(url);
- if (bitmap != null)
- imageCache.put(url, new SoftReference<Bitmap>(bitmap));
- }
- return bitmap;
- }