Android进度无法正常工作

时间:2012-11-16 11:36:21

标签: android android-asynctask android-progressbar

我是Android和Java的新手。我一直致力于我的任务,即Image Downloader。我必须使用进度条下载图像并将其显示在网格中。我创建了两个类 1. URLImageAdapter 2. CacheActivity。 一切正常但下载开始之前我点击下载按钮,当我点击下载按钮时,进度条出现,进度直到百消失但仍然下载开启。我想同步下载图像和进度条。

以下代码。任何帮助

    public class URLImageAdapter extends BaseAdapter {

private class Image {
    String url;
    Bitmap thumb;
}

private Image[] images;
private Context myContext;
private LoadThumbsTask thumbnailGen;
private Object previousList;

public URLImageAdapter(Context c) {
    myContext = c;
    thumbnailGen = new LoadThumbsTask();

    if (previousList != null) {
        images = (Image[]) previousList;
        thumbnailGen.execute(images);
        return;
    }

    images = new Image[imageURLs.length];

    for (int i = 0, j = imageURLs.length; i < j; i++) {
        images[i] = new Image();
        images[i].url = imageURLs[i];
    }

    thumbnailGen.execute(images);

}

public int getCount() {
    return images.length;
}

public Object getItem(int position) {
    return images[position].url;
}

public long getItemId(int position) {
    return position;
}

public Object getData() {
    if (thumbnailGen != null
            && thumbnailGen.getStatus() != AsyncTask.Status.FINISHED) {
        thumbnailGen.cancel(true);
    }

    return images;
}

public View getView(int position, View convertView, ViewGroup parent) {

    ImageView imgView;

    Image cached = images[position];

    if (convertView == null) {

        imgView = new ImageView(myContext);
        imgView.setLayoutParams(new GridView.LayoutParams(100, 100));

    } else {

        imgView = (ImageView) convertView;

    }

    if (cached.thumb == null) {

        imgView.setImageResource(R.drawable.ic_action_search);
        imgView.setScaleType(ScaleType.CENTER);

    } else {

        imgView.setScaleType(ScaleType.FIT_CENTER);
        imgView.setImageBitmap(cached.thumb);

    }

    return imgView;
}

private void cacheUpdated() {
    this.notifyDataSetChanged();
}


private Bitmap loadThumb(String url) {

    Bitmap thumb = null;

    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inSampleSize = 4;

    try {

        URL u = new URL(url);
        URLConnection c = u.openConnection();
        c.connect();

        BufferedInputStream stream = new BufferedInputStream(
                c.getInputStream());

        thumb = BitmapFactory.decodeStream(stream, null, opts);


        stream.close();

    } catch (MalformedURLException e) {
        Log.e("ERROR", "malformed url: " + url);
    } catch (IOException e) {
        Log.e("ERROR", "An error has occurred downloading the image: "
                + url);
    }

    return thumb;
}

private class LoadThumbsTask extends AsyncTask<Image, Void, Void> {

    @Override
    protected Void doInBackground(Image... cache) {

        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inSampleSize = 4;

        for (Image i : cache) {

            if (isCancelled())
                return null;

            if (i.thumb != null)
                continue;

            SystemClock.sleep(500);

            i.thumb = loadThumb(i.url);

            publishProgress();
        }

        return null;

    }

    @Override
    protected void onProgressUpdate(Void... param) {
        cacheUpdated();
    }
}

private String[] imageURLs = {
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_2851.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_2944.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_2989.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3005.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3012.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3034.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3047.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3092.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3110.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3113.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3128.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3160.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3226.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3228.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3251.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3268.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3275.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3346.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3365.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3374.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3385.jpg",
        "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3392.jpg", };
  }
  

CacheActivity

public class CacheActivity extends Activity {

Button btnStartProgress;
ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();

private long fileSize = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cache);
    GridView gridview = (GridView) findViewById(R.id.grid_view);
    gridview.setAdapter(new URLImageAdapter(this));
    addListenerOnButton();

    }



public void addListenerOnButton() {

    btnStartProgress = (Button) findViewById(R.id.btnStartProgress);
    btnStartProgress.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {

            progressBar = new ProgressDialog(v.getContext());
            progressBar.setCancelable(true);
            progressBar.setMessage("File downloading ...");
            progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressBar.setProgress(0);
            progressBar.setMax(100);
            progressBar.show();

            progressBarStatus = 0;

            fileSize = 0;

            new Thread(new Runnable() {
                public void run() {
                    while (progressBarStatus < 100) {

                        progressBarStatus = doInBackground();

                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        progressBarHandler.post(new Runnable() {
                            public void run() {
                                progressBar.setProgress(progressBarStatus);
                            }
                        });
                    }

                    if (progressBarStatus >= 100) {

                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        progressBar.dismiss();
                    }
                }
            }).start();

        }

    });

}

public int doInBackground() {

    while (fileSize <= 1000000) {

        fileSize++;

        if (fileSize == 100000) {
            return 10;
        } else if (fileSize == 200000) {
            return 20;
        } else if (fileSize == 300000) {
            return 30;
        }else if (fileSize == 400000) {
            return 40;
        }else if (fileSize == 500000) {
            return 50;
        }else if (fileSize == 600000) {
            return 60;
        }else if (fileSize == 700000) {
            return 70;
        }else if (fileSize == 800000) {
            return 80;
        }else if (fileSize == 900000) {
            return 90;
        }

    }

    return 100;

}

}

4 个答案:

答案 0 :(得分:1)

使用

下载图片
public class LoginProgress extends AsyncTask<Object, Object, Object> {
       private ProgressDialog dialog;
          @Override
            protected void onPreExecute() {
            this.dialog = ProgressDialog.show(applicationContext, "Please wait down",
                "Loading .....", true);
                    }
                @Override
                protected Object doInBackground(Object... params) {
                    // TODO Auto-generated method stub
                    return null;
                }
                @Override
                protected void onPostExecute(Void unused) {
        //Intent for next activity
         this.dialog.dismiss();
        }

            }

在按钮单击

中为这些类创建对象
  LoginProgress task = new LoginProgress();
    task.execute();

在这些doinbackground方法中调用你的doinbackground方法

否则请遵循以下两个

Thread.sleep(1000)的增量时间;改为Thread.sleep(4000);                       了Thread.sleep(200);更改为Thread.sleep(450);

你设置gridview.setAdapter(new URLImageAdapter(CacheActivity.this));           在oncreate中,在oncreate中删除此适配器并在点击方法结束时写入...

答案 1 :(得分:0)

根据我的经验,当它在listview或gridview中时,Progressbar有刷新问题,如果你只是想表明进度我建议开发你自己的控件,看起来像使用RelativeLayout的进度条。

采取relativelayout并添加imageview。并增加imageview的宽度以说明进展。

如果您愿意,我可以发布代码,我已经为自己开发了一个这样的进展

更新:我发现相同的帖子,以下帖子表示我描述的相同技术。

http://blog.mediarain.com/2011/04/android-custom-progressbar-with-rounded-corners/

演示可下载:http://blog.mediarain.com/wp-content/uploads/2011/04/RoundedProgressSample.zip

我希望以上内容对您有所帮助 谢谢。

答案 2 :(得分:0)

问题是您没有将任何值传递给publishProgress()的{​​{1}} 将一些值传递给此方法(例如已下载的拇指的数量),然后在LoadThumbsTask中根据此值更新您的onProgressUpdate()

答案 3 :(得分:0)

public int doInBackground() {

while (fileSize <= 1000000) {

    fileSize++;

    if (fileSize == 100000) {
        return 10;
    } else if (fileSize == 200000) {
        return 20;
    } else if (fileSize == 300000) {
        return 30;
    }else if (fileSize == 400000) {
        return 40;
    }else if (fileSize == 500000) {
        return 50;
    }else if (fileSize == 600000) {
        return 60;
    }else if (fileSize == 700000) {
        return 70;
    }else if (fileSize == 800000) {
        return 80;
    }else if (fileSize == 900000) {
        return 90;
    }

}

return 100;

}

它与实际文件大小无关。它应该像

return (currentFilesize/totalFilesize)*100 

而不仅仅是这些原始值。