我有一个类来管理将文件下载/上传到云上的远程服务。此类实现一个侦听器,该侦听器通知操作何时完成(文件上载/下载完成,或上载/下载一组文件)。
创建了一个ProgressDialog来显示操作的进度。当下载/上传管理器调用侦听器时,将填充进度条。
用户转动屏幕时出现问题。在这些情况下,我可以保存进度条的当前状态,但是如何保持对上传/下载监听器的引用?
编辑:当用户转动屏幕时,进度条消失,因为活动中的用户界面已重新加载。下载/上载过程正常继续,直到完成并调用方法“progressBar.dismiss()”。然后出现异常,因为进度条不再存在。
解决方案:按照此link获取使用片段的解决方案。
UploadDownloadListener.java
public interface UploadDownloadListener {
void operationFinished(File file);
void operationFinished();
}
UploadDownloadManager.java
public void downloadAll(final UploadDownloadListener uploadDownloadListener) {
... on file downloaded ...
uploadDownloadListener.operationFinished(file);
... on all files downloaded ...
uploadDownloadListener.operationFinished();
}
MyActivity.java
public class MyActivity extends FragmentActivity {
private ProgressDialog progressBar;
private Handler progressBarbHandler = new Handler();
...
private void createAndShowProgressDialog(View view, int numberOfFiles, CharSequence title) {
Log.i(TAG, "Create progress dialog. title [" + title + "] max[" + numberOfFiles + "]");
progressBar = new ProgressDialog(view.getContext());
progressBar.setCancelable(false);
progressBar.setMessage(title);
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(numberOfFiles);
progressBar.show();
}
private class ButtonDownloadOnClickListener implements View.OnClickListener {
@Override
public void onClick(View view) {
final int numberOfFiles = getFileToDownload.size();
createAndShowProgressDialog(view, numberOfFiles, getResources().getText(R.string.label_download));
new Thread(new Runnable() {
@Override
public void run() {
uploadDownloadManager.uploadAll(getFileToDownload(), getUploadDownloadListener());
}
}).start();
}
private UploadDownloadListener getUploadDownloadListener() {
return new UploadDownloadListener() {
int item = 0;
@Override
public void operationFinished(File file) {
item++;
progressBarbHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(item);
}
});
}
@Override
public void operationFinished() {
sleep(2000);
progressBar.dismiss();
returnToMainActivity();
}
};
}
答案 0 :(得分:0)
我正在解决这样的问题的方法是使整个类asyncTask然后在ui类中创建一个公共变量,并从asyncTask类中的post,pre和on progress update类更新ui。 / p>