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)