Android: AsyncTask,如何更新ProgressDialog的进度?

6

我想解析一个网页并可视化一个进度对话框样式的水平条,逐字节递增,这是可能的吗?


是的,这是可能的 http://goo.gl/eeiu5 - Matthieu
请参考以下示例链接: https://sites.google.com/site/androidhowto/how-to-1/create-a-custom-progress-bar-using-asynctask - Uttam
谢谢您的回答。如果我想从URL和PHP页面导入来自MySQL数据库的5000条记录,我能计算JSONArray的字节数吗?在这种情况下,我该如何应用此代码?谢谢 - MimmoG
尝试使用此函数:- getJSONArraypublic JSONArray getJSONArray(int index) throws JSONException 获取与索引关联的JSONArray。 参数: 索引 - 索引必须介于0和length() - 1之间。 返回值: 一个JSONArray值。 抛出: JSONException - 如果索引没有值。或者如果该值不是JSONArray,最后遵循此[链接](http://www.json.org/javadoc/org/json/JSONArray.html) - Uttam
但是用这段代码,我可以知道JSONArray的字节维度吗? - MimmoG
1个回答

20

尝试类似这样的操作,

创建一个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" />

在某些URL中,您将始终获得-1,然后使用此代码HttpURLConnection connection =(HttpURLConnection)url.openConnection(); connection.setRequestMethod(“HEAD”); connection.connect(); int length = connection.getContentLength(); - Parag Chauhan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接