问题描述
- Android进程条从0跳到100
-
AsyncTask
代码如下,文件更新什么的都正常,就是想实现一个进度条时,直接从0跳到100了。怎么办?
public class UploadingAsync extends AsyncTask<String, Integer, Object> { ProgressDialog dialog; BaseActivity base; public FileUploadAsyncTask(BaseActivity base) { this.base = base; } @Override protected Object doInBackground(String... path) { try { DroplrApp api = ((DroplrApplication) base.getApplication()).getDroplrAppApi(); File file = new File(path[0]); Log.e("File uploaded", file.getAbsolutePath().toString()); api.upload(file, new DroplrAppProgressListener() { @Override public void transferred(long transfer, long total) { publishProgress((int) (total * 100 / transfer)); } }); } catch (DroplrAppException e) { Log.e("Something is wrong", "Problem uploading"); } return null; } @Override protected void onPreExecute() { super.onPreExecute(); dialog = new ProgressDialog(base); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.setMessage("Uploading..."); dialog.setIndeterminate(false); dialog.setCancelable(false); dialog.setMax(100); dialog.setProgress(0); dialog.show(); } @Override protected void onPostExecute(Object result) { super.onPostExecute(result); dialog.dismiss(); } @Override protected void onProgressUpdate(Integer... progress) { super.onProgressUpdate(progress); Log.e("progress", progress[0].toString()); dialog.setProgress(progress[0]); } }
Log.e("progress", progress[0].toString()); 的输出:
前面都省略了。 06-08 15:24:13.223: E/progress(13418): 102 06-08 15:24:13.223: E/progress(13418): 102 06-08 15:24:13.223: E/progress(13418): 101 06-08 15:24:13.223: E/progress(13418): 101 06-08 15:24:13.223: E/progress(13418): 100 06-08 15:24:13.603: E/progress(13418): 100
06-08 15:24:13.648: E/progress(13418): 100
解决方案
这行:
publishProgress((int) (total * 100 / transfer));
应该是:
(int)(((float)transfer * 100f) / (float)total)
时间: 2024-10-27 16:37:26