【问题标题】:Android : AsyncTask, how can update ProgressDialog incrementAndroid:AsyncTask,如何更新 ProgressDialog 增量
【发布时间】:2016-02-10 22:35:06
【问题描述】:

我想解析一个网页并将一个progressdialog样式水平可视化并逐字节递增,这是可能的吗?

【问题讨论】:

  • 是的,有可能goo.gl/eeiu5
  • 感谢您的回答。如果我想从 mysql db 的 url 和 php 页面导入 5000 条记录,我可以以字节为单位计算 JSONArray 吗?在这种情况下如何应用此代码?谢谢
  • 试试这个函数:- getJSONArray public JSONArray getJSONArray(int index) throws JSONException 获取与索引关联的 JSONArray。参数: index - 索引必须介于 0 和 length() - 1 之间。 返回: JSONArray 值。抛出: JSONException - 如果索引没有值。或者如果该值不是 JSONArray 并且最后遵循此 link
  • 但是通过这段代码我可以知道 JSONArray 的字节数?

标签: android android-asynctask progressdialog


【解决方案1】:

试试这样的,

创建一个 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");连接.连接(); int 长度 = connection.getContentLength();
猜你喜欢
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多