ProgressBar在下载时闪烁

时间:2014-05-21 09:45:49

标签: android android-asynctask android-progressbar

我正在使用进度条显示下载进度。这是我的代码: -

@Override
    protected String doInBackground(String... f_url) {
        int count;

        Looper.prepare();
        Boolean check_sd_card_mounted = android.os.Environment
                .getExternalStorageState().equals(
                        android.os.Environment.MEDIA_MOUNTED);
        ConnectivityManager cm = (ConnectivityManager) mcontext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
        boolean isConnected = false;
        if (activeNetworkInfo != null) {
            isConnected = activeNetworkInfo.isConnected();
        }
        if (check_sd_card_mounted) {
            if (!isConnected) {
                try {
                    return "no Connection";
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                download(f_url[0]);
            }
        }

        return null;
    }

    /**
     * Updating progress bar
     * **/
    @Override
    protected void onProgressUpdate(Integer... values) {
        // TODO Auto-generated method stub
        progressBar.setVisibility(View.VISIBLE);
        progressBar.setIndeterminate(false);
        progressBar.setMax(100);
        progressBar.setProgress(values[0]);

        pinProgress.setProgress(values[0]);
        updatePinProgressContentDescription(pinProgress);
    }

以下是download()和copy()函数,我从中调用publishProgress()来更新进度条

private long download(String url) {
        int bytesCopied = 0;
        try {

            client = new DefaultHttpClient();
            httpGet = new HttpGet(url);
            response = client.execute(httpGet);
            totalSize = response.getEntity().getContentLength();
            File file = new File(Environment.getExternalStorageDirectory()
                    + "/" + "MyFile1.pdf");
            if (file.exists() && totalSize == file.length()) {

                Toast.makeText(mcontext, "File already downloaded",
                        Toast.LENGTH_LONG).show();

            } else if (file.exists()) {
                httpGet.addHeader("Range", "bytes=" + file.length() + "-");
                client = new DefaultHttpClient();

                httpGet = new HttpGet(url);
                response = client.execute(httpGet);
            }
            outputStream = new ProgressReportingRandomAccessFile(file, "rw");
            publishProgress(0, (int) totalSize);
            InputStream input = response.getEntity().getContent();
            bytesCopied = copy(input, outputStream);

        } catch (Exception e) {
            Toast.makeText(mcontext, e.getMessage(), Toast.LENGTH_LONG)
                    .show();
        }
        return bytesCopied;
    }

    public int copy(InputStream input, RandomAccessFile out)
            throws IOException, NetworkErrorException {

        if (input == null || out == null) {
            return -1;
        }

        byte[] buffer = new byte[8192];

        BufferedInputStream in = new BufferedInputStream(input, 8192);

        int count = 0, n = 0;
        long errorBlockTimePreviousTime = -1, expireTime = 0;
        long total = 0;
        try {

            byte data[] = new byte[8192];
            while (!interrupt && (count = in.read(data)) != -1) {
                out.seek(out.length());
                myProgress = (int) (((long) total * 100) / totalSize);
                publishProgress(myProgress);
                total += count;
                // while (!interrupt) {
                // n = in.read(data, 0, 8192);
                if (n == -1) {
                    break;
                }
                out.write(data, 0, count);
                // count += n;
            }
            IsDownlodComplete = true;
        } finally {
            // must close client first
            client = null;
            out.close();
            in.close();
            input.close();
        }
        return count;

    }

ProgressBar更新但闪烁但不清楚。我在onProgressUpdate中更新它,它在UI线程上运行但仍然闪烁。我不知道为什么?

提前致谢。

1 个答案:

答案 0 :(得分:0)

尝试将onProgressUpdate()缩减为:

@Override
protected void onProgressUpdate(Integer... values) {
    progressBar.setProgress(values[0]);
    pinProgress.setProgress(values[0]);
    updatePinProgressContentDescription(pinProgress);
}

将进度条初始化内容放入onPreExecute()。重复初始化会导致闪烁。

@Override
protected void onPreExecute() {
    progressBar.setVisibility(View.VISIBLE);
    progressBar.setIndeterminate(false);
    progressBar.setMax(100);
}