Android中的AsyncTask:如何使用背景图像设置ProgressBar?

Android中的AsyncTask:如何使用背景图像设置ProgressBar?,android,android-asynctask,Android,Android Asynctask,如何使用Asynctask(onPreExecute()方法)使第一个应用程序看起来像BBC新闻android应用程序。请帮助我我的助手类代码在这里 UrlImageViewHelper.java package com.warriorpoint.androidxmlsimple; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOExce

如何使用Asynctask(onPreExecute()方法)使第一个应用程序看起来像BBC新闻android应用程序。请帮助我我的助手类代码在这里

UrlImageViewHelper.java

package com.warriorpoint.androidxmlsimple;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Hashtable;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;

import android.app.Activity;

import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.util.DisplayMetrics;

import android.widget.ImageView;

public final class UrlImageViewHelper {
    private static final String LOGTAG = "UrlImageViewHelper";
    public static int copyStream(InputStream input, OutputStream output) throws IOException
    {
        byte[] stuff = new byte[1024];
        int read = 0;
        int total = 0;
        while ((read = input.read(stuff)) != -1)
        {
            output.write(stuff, 0, read);
            total += read;
        }
        return total;
    }

    static Resources mResources;
    static DisplayMetrics mMetrics;
    private static void prepareResources(Context context) {
        if (mMetrics != null)
            return;
        mMetrics = new DisplayMetrics();
        Activity act = (Activity)context;
        act.getWindowManager().getDefaultDisplay().getMetrics(mMetrics);
        AssetManager mgr = context.getAssets();
        mResources = new Resources(mgr, mMetrics, context.getResources().getConfiguration());
    }

    private static BitmapDrawable loadDrawableFromStream(Context context, InputStream stream) {
        prepareResources(context);
        final Bitmap bitmap = BitmapFactory.decodeStream(stream);
        //Log.i(LOGTAG, String.format("Loaded bitmap (%dx%d).", bitmap.getWidth(), bitmap.getHeight()));
        return new BitmapDrawable(mResources, bitmap);
    }

    public static final int CACHE_DURATION_INFINITE = Integer.MAX_VALUE;
    public static final int CACHE_DURATION_ONE_DAY = 1000 * 60 * 60 * 24;
    public static final int CACHE_DURATION_TWO_DAYS = CACHE_DURATION_ONE_DAY * 2;
    public static final int CACHE_DURATION_THREE_DAYS = CACHE_DURATION_ONE_DAY * 3;
    public static final int CACHE_DURATION_FOUR_DAYS = CACHE_DURATION_ONE_DAY * 4;
    public static final int CACHE_DURATION_FIVE_DAYS = CACHE_DURATION_ONE_DAY * 5;
    public static final int CACHE_DURATION_SIX_DAYS = CACHE_DURATION_ONE_DAY * 6;
    public static final int CACHE_DURATION_ONE_WEEK = CACHE_DURATION_ONE_DAY * 7;

    public static void setUrlDrawable(final ImageView imageView, final String url, int defaultResource) {
        setUrlDrawable(imageView.getContext(), imageView, url, defaultResource, CACHE_DURATION_THREE_DAYS);
    }

    public static void setUrlDrawable(final ImageView imageView, final String url) {
        setUrlDrawable(imageView.getContext(), imageView, url, null, CACHE_DURATION_THREE_DAYS);
    }

    public static void loadUrlDrawable(final Context context, final String url) {
        setUrlDrawable(context, null, url, null, CACHE_DURATION_THREE_DAYS);
    }

    public static void setUrlDrawable(final ImageView imageView, final String url, Drawable defaultDrawable) {
        setUrlDrawable(imageView.getContext(), imageView, url, defaultDrawable, CACHE_DURATION_ONE_DAY);
    }

    public static void setUrlDrawable(final ImageView imageView, final String url, int defaultResource, long cacheDurationMs) {
        setUrlDrawable(imageView.getContext(), imageView, url, defaultResource, cacheDurationMs);
    }

    public static void loadUrlDrawable(final Context context, final String url, long cacheDurationMs) {
        setUrlDrawable(context, null, url, null, cacheDurationMs);
    }

    public static void setUrlDrawable(final ImageView imageView, final String url, Drawable defaultDrawable, long cacheDurationMs) {
        setUrlDrawable(imageView.getContext(), imageView, url, defaultDrawable, cacheDurationMs);
    }

    private static void setUrlDrawable(final Context context, final ImageView imageView, final String url, int defaultResource, long cacheDurationMs) {
        Drawable d = null;
        if (defaultResource != 0)
            d = imageView.getResources().getDrawable(defaultResource);
        setUrlDrawable(context, imageView, url, d, cacheDurationMs);
    }

    private static boolean isNullOrEmpty(CharSequence s) {
        return (s == null || s.equals("") || s.equals("null") || s.equals("NULL"));
    }

    private static boolean mHasCleaned = false;

    public static String getFilenameForUrl(String url) {
        return "" + url.hashCode() + ".urlimage";
    }

    private static void cleanup(Context context) {
        if (mHasCleaned)
            return;
        mHasCleaned = true;
        try {
            // purge any *.urlimage files over a week old
            String[] files = context.getFilesDir().list();
            if (files == null)
                return;
            for (String file : files) {
                if (!file.endsWith(".urlimage"))
                    continue;

                File f = new File(context.getFilesDir().getAbsolutePath() + '/' + file);
                if (System.currentTimeMillis() > f.lastModified() + CACHE_DURATION_ONE_WEEK)
                    f.delete();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void setUrlDrawable(final Context context, final ImageView imageView, final String url, final Drawable defaultDrawable, long cacheDurationMs) {
        cleanup(context);
        // disassociate this ImageView from any pending downloads
        if (imageView != null)
            mPendingViews.remove(imageView);

        if (isNullOrEmpty(url)) {
            if (imageView != null)
                imageView.setImageDrawable(defaultDrawable);
            return;
        }

        final UrlImageCache cache = UrlImageCache.getInstance();
        Drawable d = cache.get(url);
        if (d != null) {
            //Log.i(LOGTAG, "Cache hit on: " + url);
            if (imageView != null)
                imageView.setImageDrawable(d);
            return;
        }

        final String filename = getFilenameForUrl(url);

        File file = context.getFileStreamPath(filename);
        if (file.exists()) {
            try {
                if (cacheDurationMs == CACHE_DURATION_INFINITE || System.currentTimeMillis() < file.lastModified() + cacheDurationMs) {
                    //Log.i(LOGTAG, "File Cache hit on: " + url + ". " + (System.currentTimeMillis() - file.lastModified()) + "ms old.");
                    FileInputStream  fis = context.openFileInput(filename);
                    BitmapDrawable drawable = loadDrawableFromStream(context, fis);
                    fis.close();
                    if (imageView != null)
                        imageView.setImageDrawable(drawable);
                    cache.put(url, drawable);
                    return;
                }
                else {
                    //Log.i(LOGTAG, "File cache has expired. Refreshing.");
                }
            }
            catch (Exception ex) {
            }
        }

        // null it while it is downloading
        if (imageView != null)
            imageView.setImageDrawable(defaultDrawable);

        // since listviews reuse their views, we need to 
        // take note of which url this view is waiting for.
        // This may change rapidly as the list scrolls or is filtered, etc.
        //Log.i(LOGTAG, "Waiting for " + url);
        if (imageView != null)
            mPendingViews.put(imageView, url);

        ArrayList<ImageView> currentDownload = mPendingDownloads.get(url);
        if (currentDownload != null) {
            // Also, multiple vies may be waiting for this url.
            // So, let's maintain a list of these views.
            // When the url is downloaded, it sets the imagedrawable for
            // every view in the list. It needs to also validate that
            // the imageview is still waiting for this url.
            if (imageView != null)
                currentDownload.add(imageView);
            return;
        }

        final ArrayList<ImageView> downloads = new ArrayList<ImageView>();
        if (imageView != null)
            downloads.add(imageView);
        mPendingDownloads.put(url, downloads);

        AsyncTask<Void, Void, Drawable> downloader = new AsyncTask<Void, Void, Drawable>() {



            @Override
            protected Drawable doInBackground(Void... params) {
                AndroidHttpClient client = AndroidHttpClient.newInstance(context.getPackageName());
                try {
                    HttpGet get = new HttpGet(url);
                    final HttpParams httpParams = new BasicHttpParams();
                    HttpClientParams.setRedirecting(httpParams, true);
                    get.setParams(httpParams);
                    HttpResponse resp = client.execute(get);
                    int status = resp.getStatusLine().getStatusCode();
                    if(status != HttpURLConnection.HTTP_OK){
//                        Log.i(LOGTAG, "Couldn't download image from Server: " + url + " Reason: " + resp.getStatusLine().getReasonPhrase() + " / " + status);
                        return null;
                    }
                    HttpEntity entity = resp.getEntity();
//                    Log.i(LOGTAG, url + " Image Content Length: " + entity.getContentLength());
                    InputStream is = entity.getContent();
                    FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
                    copyStream(is, fos);
                    fos.close();
                    is.close();
                    FileInputStream  fis = context.openFileInput(filename);
                    return loadDrawableFromStream(context, fis);
                }
                catch (Exception ex) {
//                    Log.e(LOGTAG, "Exception during Image download of " + url, ex);
                    return null;
                }
                finally {
                    client.close();
                }
            }


            @Override
            protected void onPostExecute(Drawable result) {
                if (result == null)
                    result = defaultDrawable;
                mPendingDownloads.remove(url);
                cache.put(url, result);
                for (ImageView iv: downloads) {
                    // validate the url it is waiting for
                    String pendingUrl = mPendingViews.get(iv);
                    if (!url.equals(pendingUrl)) {
                        //Log.i(LOGTAG, "Ignoring out of date request to update view for " + url);
                        continue;
                    }
                    mPendingViews.remove(iv);
                    if (result != null) {
                        final Drawable newImage = result;

                        Drawable newSize=resize(newImage);


                        final ImageView imageView = iv;

                        imageView.setImageDrawable(newSize);
                    }
                }
            }

            private BitmapDrawable resize(Drawable newImage) {
                // TODO Auto-generated method stub

                Bitmap d = ((BitmapDrawable)newImage).getBitmap();
                Bitmap bitmapOrig = Bitmap.createScaledBitmap(d, 75, 75, false);
                return new BitmapDrawable(bitmapOrig);                                              
            }
        };
        downloader.execute();
    }



    private static Hashtable<ImageView, String> mPendingViews = new Hashtable<ImageView, String>();
    private static Hashtable<String, ArrayList<ImageView>> mPendingDownloads = new Hashtable<String, ArrayList<ImageView>>();
}
package com.warriorpoint.androidxmlsimple;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入java.net.HttpURLConnection;
导入java.util.ArrayList;
导入java.util.Hashtable;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.client.params.HttpClientParams;
导入org.apache.http.params.BasicHttpParams;
导入org.apache.http.params.HttpParams;
导入android.app.Activity;
导入android.content.Context;
导入android.content.res.AssetManager;
导入android.content.res.Resources;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.graphics.drawable.BitmapDrawable;
导入android.graphics.drawable.drawable;
导入android.net.http.AndroidHttpClient;
导入android.os.AsyncTask;
导入android.util.DisplayMetrics;
导入android.widget.ImageView;
公共最终类UrlImageViewHelper{
私有静态最终字符串LOGTAG=“UrlImageViewHelper”;
公共静态int copyStream(InputStream输入,OutputStream输出)引发IOException
{
byte[]stuff=新字节[1024];
int read=0;
int-total=0;
而((read=input.read(stuff))!=-1)
{
输出.写入(填充,0,读取);
总计+=读取;
}
返回总数;
}
静态资源;
静态显示矩阵;
私有静态void prepareResources(上下文){
如果(mMetrics!=null)
回来
mMetrics=新的DisplayMetrics();
活动行为=(活动)上下文;
act.getWindowManager().getDefaultDisplay().getMetrics(mMetrics);
AssetManager mgr=context.getAssets();
mResources=新资源(mgr、mMetrics、context.getResources().getConfiguration());
}
私有静态BitmapDrawable loadDrawableFromStream(上下文上下文,InputStream流){
准备资料(背景);
最终位图位图=BitmapFactory.decodeStream(流);
//Log.i(LOGTAG,String.format(“加载的位图(%dx%d)”,bitmap.getWidth(),bitmap.getHeight());
返回新的BitmapDrawable(mResources,位图);
}
public static final int CACHE_DURATION_INFINITE=Integer.MAX_值;
公共静态最终整数缓存持续时间一天=1000*60*60*24;
公共静态最终整数缓存持续时间两天=缓存持续时间一天*2;
公共静态最终整数缓存持续时间三天=缓存持续时间一天*3;
公共静态最终整数缓存持续时间四天=缓存持续时间一天*4;
公共静态最终整数缓存持续时间五天=缓存持续时间一天*5;
公共静态最终整数缓存持续时间六天=缓存持续时间一天*6;
公共静态最终整数缓存持续时间一周=缓存持续时间一天*7;
公共静态void setUrlDrawable(最终ImageView ImageView、最终字符串url、int-defaultResource){
setUrlDrawable(imageView.getContext()、imageView、url、defaultResource、缓存\u持续时间\u三天);
}
公共静态void setUrlDrawable(最终图像视图,最终字符串url){
setUrlDrawable(imageView.getContext(),imageView,url,null,缓存持续时间三天);
}
公共静态void loadUrlDrawable(最终上下文,最终字符串url){
setUrlDrawable(上下文、空、url、空、缓存持续时间三天);
}
公共静态void setUrlDrawable(最终ImageView ImageView,最终字符串url,可绘制defaultDrawable){
setUrlDrawable(imageView.getContext(),imageView,url,defaultDrawable,缓存持续时间一天);
}
公共静态void setUrlDrawable(最终ImageView ImageView、最终字符串url、int-defaultResource、长缓存持续时间ms){
setUrlDrawable(imageView.getContext()、imageView、url、defaultResource、cacheDurationMs);
}
公共静态void loadUrlDrawable(最终上下文上下文、最终字符串url、长缓存持续时间){
setUrlDrawable(上下文、null、url、null、cacheDurationMs);
}
公共静态void setUrlDrawable(最终ImageView ImageView、最终字符串url、可绘制defaultDrawable、长缓存持续时间ms){
setUrlDrawable(imageView.getContext(),imageView,url,defaultDrawable,cacheDurationMs);
}
私有静态void setUrlDrawable(最终上下文上下文、最终ImageView ImageView、最终字符串url、int-defaultResource、长缓存持续时间ms){
可提取d=null;
如果(默认资源!=0)
d=imageView.getResources().getDrawable(defaultResource);
setUrlDrawable(上下文、imageView、url、d、cacheDurationMs);
}
私有静态布尔值isNullOrEmpty(字符序列){
返回(s==null | | s.equals(“”| | s.equals(“null”)| | s.equals(“null”);
}
私有静态布尔值mhasclean=false;
公共静态字符串getFilenameForUrl(字符串url){
返回“+url.hashCode()+”.urlimage”;
}
专用静态空洞清理(上下文){
如果(MHA)
回来
mhasclean=true;
试一试{
//清除超过一周的所有*.urlimage文件
String[]files=context.getFilesDir().list();
if(files==null)
回来
用于(字符串文件:文件){
如果(!file.endsWith(“.urlimage”))
持续
文件f=新文件(context.getFilesDir().getAbsolutePath()+'/'+文件);
if(System.currentTimeMillis()>f.lastModified()+缓存持续时间一周)
f、 删除();
}
}
捕获(Exc)
private final ProgressDialog dialog = new ProgressDialog(this.context);
    @Override
    protected void onPreExecute() {
          this.dialog.setMessage("Fecthing Image");
          this.dialog.setTitle("Please Wait");
          this.dialog.setIcon(R.drawable."Any Image here");
          this.dialog.show();
    }