2 woshiwoxingfu woshiwoxingfu 于 2012.11.19 14:00 提问

android进程不能同步工作

我刚接触android和java。我一直在做这个东西,就是图片下载器。我下载图片,然后用进度条显示下载进度,并用网格显示出来。我已经创建了两个class 1.URLImageAdapter2.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;

}

}

2个回答

niangzhi
niangzhi   2012.11.19 14:33
已采纳

下载正在使用中的图片

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) {
                    return null;
                }
                @Override
                protected void onPostExecute(Void unused) {
         this.dialog.dismiss();
        }

            }

给那些按钮点击时的类创建对象

  LoginProgress task = new LoginProgress();
    task.execute();

在这些doinbackground方法调用你的doinbackground方法
否则的话就做下边这两步
增加时间Thread.sleep(1000改为Thread.sleep(4000); Thread.sleep(200改为Thread.sleep(450);

你在oncreate设置gridview.setAdapter(new URLImageAdapter(CacheActivity.this)); , 在oncreate移除这个适配器然后在你的点击方法的结尾写它。上边的代码是我之前做过的,和你的问题类似。你还可以看看这个http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/

Sueyexin
Sueyexin   2012.11.19 15:04
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 

而不仅仅是原始的数据,就像这样。

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!