Android图片异步加载

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
  
import com.mosjoy.ad.MosJoyAdApplication;
import com.mosjoy.ad.R;
import com.mosjoy.ad.utils.FileCache;
import com.mosjoy.ad.utils.ImageCache;
import com.mosjoy.ad.utils.Utils;
  
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.StatFs;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
  
/**
 * 图片异步加载工具类
 * @author zouyb
 *
 */
public class RemoteImageView extends ImageView {
  
    /**
     * 下载失败最大重复次数
     */
    private static int MAX_FAILURES = 3;
  
    /**
     * 下载图片网址
     */
    private String mUrl;
  
    /**
     * 当前下载成功图片网址
     */
    private String mCurrentlyGrabbedUrl;
  
    /**
     * 下载失败次数
     */
    private int mFailure;
  
    /**
     * 默认图片资源id
     */
    private Integer mDefaultImage;
  
    /**
     * 上下文
     */
    private Context mContext;
      
    /**
     *  文件操作
     */
    private FileCache fileCache;
  
    private final static int MB = 1048576;
      
    //图片宽度
    private int pwidth=-1;
    //图片高度
    private int pheight=-1;
    //是否显示默认图片
    private boolean isShowDefault=false;
    public RemoteImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
        init();
    }
  
    public RemoteImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init();
    }
  
    public RemoteImageView(Context context) {
        super(context);
        mContext = context;
        init();
    }
  
    /**
     * Sharable code between constructors
     */
    private void init() {
        fileCache = new FileCache(mContext);
    }
  
    public void setImageUrl(String url) {
        System.out.println("width="+pwidth+",height="+pheight);
        System.out.println("url="+url);
        if(("").equals(url) || url == null||url.contains("null")){
            if(isShowDefault){
                setImageResource(R.drawable.default_image);
            }else{
                setVisibility(View.GONE);
            }
            return;
        }
        setVisibility(View.VISIBLE);
        url = url.replace("\\", "/");
        mUrl = url;
        MosJoyAdApplication instance = MosJoyAdApplication.getInstance();
        ImageCache imageCache = instance.getImageCache();
        if (imageCache.isCached(mUrl)) {
            // 图片在缓存中
            this.setImageBitmap(imageCache.get(mUrl).get());
            Log.e(MosJoyAdApplication.TAG, "从内存加载图片 " + url);
        } else {
            File f = new File(mUrl);
            Bitmap b = decodeFile(f);
            if(b != null){
                //从内存卡加载
                this.setImageBitmap(b);
                imageCache.put(mUrl,new SoftReference<Bitmap>(b));
                Log.e(MosJoyAdApplication.TAG, "从本地加载图片 " + url);
            }else{
                //防止重复下载
                //if(YYQMusicApplication.getInstance().getDownLoadImageList().contains(mUrl)) return;
                //下载图片
                Log.e(MosJoyAdApplication.TAG, "从网络下载图片 " + url);
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("url", mUrl);
                map.put("file", f);
                try{
                    new DownloadTask().execute(map);
                }catch(Exception e){}
            }
        }
  
    }
  
    public void setDefaultImage(Integer resid) {
        mDefaultImage = resid;
    }
  
    private void loadDefaultImage() {
        if (mDefaultImage != null)
            setImageResource(mDefaultImage);
    }
      
    class DownloadTask extends AsyncTask<Map<String, Object>,Void, Bitmap>{
  
        private String mTaskUrl;
        private File f;
          
        @Override
        public void onPreExecute() {
            loadDefaultImage();
            super.onPreExecute();
        }
          
        @Override
        protected Bitmap doInBackground(Map<String, Object>... params) {
            mTaskUrl = params[0].get("url").toString();
            //YYQMusicApplication.getInstance().getDownLoadImageList().add(mTaskUrl);
            f = (File) params[0].get("file");
            try {
                Bitmap bitmap=null;
                URL imageUrl = new URL(mTaskUrl);
                HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
                conn.setConnectTimeout(30000);
                conn.setReadTimeout(30000);
                InputStream is=conn.getInputStream();
                OutputStream os = new FileOutputStream(f);
                Utils.CopyStream(is, os);
                os.close();
                bitmap = decodeFile(f);
                return bitmap;
            } catch(FileNotFoundException fileNotFoundException){
                fileNotFoundException.printStackTrace();
                return null;
            }
            catch (Exception ex){
               ex.printStackTrace();
            }
            return null;
        }
          
        @Override
        public void onPostExecute(Bitmap b) {
            super.onPostExecute(b);
            if(b == null){
                //下载失败,继续下载
                //RemoteImageView.this.setImageUrl(mTaskUrl);
            }else{
                //下载成功
                MosJoyAdApplication.getInstance().getImageCache().put(mTaskUrl, new SoftReference<Bitmap>(b));
                RemoteImageView.this.setImageBitmap(b);           
                mCurrentlyGrabbedUrl = mTaskUrl;              
            }
        }
          
    };
  
    /**
     * 解码图片
     * @param f
     * @return
     */
    private Bitmap decodeFile(File f) {
        if(!f.exists()){
            return null;
        }
        if(pwidth>0&&pheight>0){
            System.out.println("加载缩略图");
            return decodeFile(f, pwidth, pheight);
        }
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 1;
            return BitmapFactory.decodeFile(f.getAbsolutePath(), options);
        } catch (Exception e) {
        }
        return null;
    }
  
    private int freeSpaceOnSd() {
        StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
                .getPath());
        double sdFreeMB = ((double) stat.getAvailableBlocks() * (double) stat
                .getBlockSize()) / MB;
  
        return (int) sdFreeMB;
    }
      
    private Bitmap decodeFile(File file,int width,int height){
        BitmapFactory.Options options=new BitmapFactory.Options();
        int scale=1;
        if(width>0||height>0){
            //设置次参数为true,解码时返回的Bitmap为空,不分配内存
            options.inJustDecodeBounds=true;
            BitmapFactory.decodeFile(file.getAbsolutePath(), options);
            //得到原始图片的宽度和高度
            int outWidth=options.outWidth;
            int outHeight=options.outHeight;
            while(true){
                if((width>0&&outWidth/2<width)||(height>0&&outHeight/2<height)){
                    break;
                }
                outWidth/=2;
                outHeight/=2;
                scale*=2;
            }
        }
        //缩放比例为1/scale
        options.inSampleSize=scale;
        options.inJustDecodeBounds=false;
        //处理之后,加载进内存的就是图片的缩略图
        return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
    }
  
    public void setPwidth(int pwidth) {
        this.pwidth = pwidth;
    }
  
    public void setPheight(int pheight) {
        this.pheight = pheight;
    }
  
    public void setShowDefault(boolean isShowDefault) {
        this.isShowDefault = isShowDefault;
    }
  
}