Android:AsyncTask,如何更新ProgressDialog增量

前端之家收集整理的这篇文章主要介绍了Android:AsyncTask,如何更新ProgressDialog增量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想解析一个网页并将progressdialog样式水平视觉化并逐字递增,这是可能的吗?

解决方法

尝试这样的事情,

创建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,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" />
原文链接:https://www.f2er.com/android/313814.html

猜你在找的Android相关文章