Android:AsyncTask,如何更新ProgressDialog增量 [英] Android : AsyncTask, how can update ProgressDialog increment

查看:21
本文介绍了Android:AsyncTask,如何更新ProgressDialog增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析网页并水平显示进度对话框样式并将其逐字节递增,这是可能的吗?

I want to parse a webpage and visual a progressdialog style horizontal and increment it byte to byte, it's possibile ?

推荐答案

试试这个,

创建一个 ProgressDialog.

ProgressDialog mProgressDialog = new ProgressDialog(Your_Activity.this);
mProgressDialog.setMessage("Here you can set a message");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.show();
MyAsyncTask obj = new MyAsyncTask ();
obj.execute("url");

您的 AsyncTask 类.

private class MyAsyncTask extends AsyncTask<String, Integer, String>{
    @Override
    protected String doInBackground(String... url) {
        int count;
        try {
            URL url = new URL(url[0]);
            URLConnection connection = url.openConnection();
            connection.connect();
            // this will be useful so that you can show a tipical 0-100% progress bar
            int length = connection.getContentLength();

            // downlod the file
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream("/sdcard/file_name.txt");

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                publishProgress((int)(total*100/length));
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {}
        return null;
    }
    @Override
    public void onProgressUpdate(String... args){
        mProgressDialog.setProgress(args[0]);
     }
  }
}

您必须在 AndroidManifest 文件中授予这些权限.

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

这篇关于Android:AsyncTask,如何更新ProgressDialog增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆