安卓:AsyncTask的,怎么可以更新ProgressDialog增量增量、AsyncTask、ProgressDialog

2023-09-13 00:50:04 作者:+我吥稀罕'

我想分析一个网页,视觉上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" />
 
精彩推荐