Subversion Repository Public Repository

Nextrek

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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package nextrek.widgets;

import java.lang.ref.WeakReference;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

import nextrek.lib.SICKey;
import android.R;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

public class WebImageView extends RelativeLayout {

    private static final int DEFAULT_POOL_SIZE = 3;
    private static ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(DEFAULT_POOL_SIZE, new ThreadFactory() {

        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setPriority(Thread.MIN_PRIORITY);
            return thread;
        }
    });

    private enum ImageState {
        LOADING, SET, ERROR
    }

    class loaderMessage {
        private SICKey key;
        private BitmapDrawable drawable = null;

        public loaderMessage(SICKey key) {
            this.key = key;
        }

        public String getImageUrl() {
            return key.getName();
        }

        public BitmapDrawable getDrawable() {
            return drawable;
        }

        public void setDrawable(BitmapDrawable drawable) {
            this.drawable = drawable;
        }

        public void destroy() {
            key = null;
            drawable = null;
        }
    }

    private static final int COMPLETE = 0;
    private static final int FAILED = 1;
    protected static final String TAG = "WebImageView";
    /**
     * Callback that is received once the image has been downloaded
     */
    private Handler imageLoadedHandler = new Handler(new Callback() {
        public boolean handleMessage(Message msg) {
            if ((msg == null) || ((msg.what != COMPLETE) & (msg.what != FAILED))) {
                return true;
            }

            final loaderMessage message = (loaderMessage) msg.obj;
            if (message != null) {
                final String targetUrl = (String) getImageView().getTag();
                if ((targetUrl != null) && (message.getImageUrl() != null) && (targetUrl.equals(message.getImageUrl()))) {
                    if (msg.what == COMPLETE) {

                        if (message.getDrawable() != null) {
                            setImageState(message.getDrawable(), targetUrl, ImageState.SET);
                        } else {
                            Log.e(TAG, "imageLoadedHandler: drawable is null");
                        }

                    } else {
                        if (msg.what == FAILED) {

                            setImageState(null, targetUrl, ImageState.ERROR);

                            // Could change image here to a 'failed' image
                            // otherwise will just keep on spinning
                            Log.e(TAG, "imageLoadedHandler: failed to fetch image");
                        } else {
                            Log.e(TAG, "imageLoadedHandler: received " + msg.what);
                        }
                    }
                }
            }
            message.destroy();
            return true;
        }
    });

    /**
     * Set's the view's drawable, this uses the internet to retrieve the image
     * don't forget to add the correct permissions to your manifest
     * 
     * @param imageUrl
     *            the url of the image you wish to load
     */

    private String lastUrl = "";
    private int L0_downsample = 1;

    public void setDownsample(int downsample) {
        L0_downsample = downsample;
    }

    private synchronized ImageView getImageView() {
        return (ImageView) getChildAt(1);
    }

    private synchronized ProgressBar getSpinnerView() {
        return (ProgressBar) getChildAt(0);
    }

    /**
     * This is used when creating the view in XML To have an image load in XML
     * use the tag
     * 'image="http://developer.android.com/images/dialog_buttons.png"'
     * Replacing the url with your desired image Once you have instantiated the
     * XML view you can call setImageDrawable(url) to change the image
     * 
     * @param context
     * @param attrSet
     */
    public WebImageView(final Context context, final AttributeSet attrSet) {
        super(context, attrSet);
        final String url = attrSet.getAttributeValue(null, "image");
        if (url != null) {
            instantiate(context, url);
        } else {
            instantiate(context, null);
        }
    }

    /**
     * This is used when creating the view programatically Once you have
     * instantiated the view you can call setImageDrawable(url) to change the
     * image
     * 
     * @param context
     *            the Activity context
     * @param imageUrl
     *            the Image URL you wish to load
     */
    public WebImageView(final Context context, final String imageUrl) {
        super(context);
        instantiate(context, imageUrl);
    }

    /**
     * First time loading of the LoaderImageView Sets up the LayoutParams of the
     * view, you can change these to get the required effects you want
     */
    private void instantiate(final Context context, final String imageUrl) {

        setPersistentDrawingCache(PERSISTENT_NO_CACHE);
        setDrawingCacheEnabled(false);
        destroyDrawingCache();

        ProgressBar mSpinner = new ProgressBar(context);
        mSpinner.setDrawingCacheEnabled(false);
        mSpinner.destroyDrawingCache();

        LayoutParams lp = new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
        mSpinner.setLayoutParams(lp);

        mSpinner.setIndeterminate(true);
        // mSpinner.setBackgroundColor(0x80808080);

        addView(mSpinner);

        ImageView mImage = new ImageView(context);
        mImage.setDrawingCacheEnabled(false);
        mImage.destroyDrawingCache();

        mImage.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.FILL_PARENT));
        mImage.setScaleType(ScaleType.FIT_CENTER);

        addView(mImage);

        lastUrl = "";

        if (imageUrl != null) {
            setImageUrl(imageUrl);
        } else {

            mSpinner.setVisibility(View.GONE);
        }
        if (isInEditMode()) {
            setBackgroundColor(0xFFFF0000);
        }

    }

    private synchronized void setImageState(BitmapDrawable drawable, String imageUrl, ImageState state) {
        ProgressBar spinner = getSpinnerView();
        ImageView image = getImageView();
        if (state == ImageState.LOADING) {
            if (image != null)
                image.setVisibility(View.GONE);
            if (spinner != null)
                spinner.setVisibility(View.VISIBLE);
        } else {
            if (spinner != null)
                spinner.setVisibility(View.GONE);
            if (image != null)
                image.setVisibility(View.VISIBLE);
        }
        if (image != null) {
            synchronized (image) {
                try {
                    if (state == ImageState.ERROR) {
                        image.setImageResource(R.drawable.ic_dialog_alert);
                        image.setTag(null);
                    } else {
                        image.setImageDrawable(drawable);
                        image.setTag(imageUrl);
                    }
                } finally {
                    image = null;
                }
            }
        }
    }

    private WeakReference<asyncLoad> mLastRequest = null;

    private synchronized void stopRunner() {
        if (mLastRequest != null) {
            if (mLastRequest.get() != null) {
                executor.remove(mLastRequest.get());
                mLastRequest = null;
            }
        }
    }

    private synchronized void startRunner(SICKey key) {
        mLastRequest = new WeakReference<asyncLoad>(new asyncLoad(key, new WeakReference<Handler>(imageLoadedHandler)));
        executor.execute(mLastRequest.get());
    }

    public void setImageUrl(final String imageUrl) {

        if (imageUrl == null) {
            lastUrl = "";
            stopRunner();
            setImageState(null, null, ImageState.SET);
            return;
        }

        if ((lastUrl.equals(imageUrl))) {
            // already in loaded or loading in progress
            return;
        }

        lastUrl = imageUrl;

        SICKey key = new SICKey(imageUrl, L0_downsample);

        /*
         * 1st level cache
         */
        if (key.inL0()) {
            BitmapDrawable drawable = key.getL0();
            if (drawable != null) {
                stopRunner();
                setImageState(drawable, imageUrl, ImageState.SET);
                return;
            }
        }
        /*
         * if (key.inL1()) {
         * 
         * // decode it on the fly without thread
         * BitmapDrawable drawable = key.getDrawable();
         * if (drawable != null) {
         * stopRunner();
         * setImageState(drawable, imageUrl, ImageState.SET);
         * return;
         * }
         * }
         */
        /**
         * 3rd cache & HTTP
         */
        stopRunner();
        setImageState(null, imageUrl, ImageState.LOADING);
        startRunner(key);
        key = null; // forget;
    }

    class asyncLoad implements Runnable {

        private SICKey key;
        private WeakReference<Handler> handler;

        asyncLoad(SICKey key, WeakReference<Handler> handler) {
            super();

            this.handler = handler;
            this.key = key;
        }

        @Override
        protected void finalize() throws Throwable {
            key = null;
            handler = null;
            super.finalize();
        }

        public void run() {

            BitmapDrawable drawable = null;

            drawable = key.get();

            if (drawable == null) {
                Log.e(TAG, "Error, retrying 2/3" + key.getName());
                try {
                    Thread.sleep(1000, 0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                drawable = key.get();
            }

            if (drawable == null) {
                Log.e(TAG, "Error, retrying 3/3" + key.getName());
                try {
                    Thread.sleep(1000, 0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                drawable = key.get();
            }

            loaderMessage msg = new loaderMessage(key);
            if (drawable != null) {
                msg.setDrawable(drawable);
                drawable = null;
                if (handler.get() != null)
                    handler.get().sendMessage(handler.get().obtainMessage(COMPLETE, msg));
            } else {
                Log.e(TAG, "Error, cannot retrieve: " + key.getName());

                if (handler.get() != null)
                    handler.get().sendMessage(handler.get().obtainMessage(FAILED, msg));
            }

        }

    }
}

Commits for Nextrek/Android/LibrerieNextrek/src/nextrek/widgets/WebImageView.java

Diff revisions: vs.
Revision Author Commited Message
4 FMMortaroli picture FMMortaroli Fri 19 Apr, 2013 16:54:38 +0000