屏幕旋转后,异步任务中的进度对话框不再显示

时间:2013-02-24 18:23:45

标签: android

我正在使用异步任务将图片上传到远程服务器。为了向用户显示进度,我正在使用进度对话框。此进度对话框是在异步任务类的preExecute方法中创建的。

当用户旋转屏幕时,进度对话框消失,但异步任务仍在运行。该活动包含对异步任务的静态引用,因此我知道该任务仍在运行。我现在如何再次显示进度对话框?我尝试了以下方法:

活动的创建方法:

protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);

if(task != null) {
Status status = task.getStatus();

if(status == Status.RUNNING) {
    task.updateViewContext(this);
}

}

我的异步任务类的构造函数:

public UploadTask(UploadPicturesActivity activity) {
   this.context = activity;
   dialog = new ProgressDialog(activity);
   dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);        
}   

我的asnyc任务类的preexcetue方法:

protected void onPreExecute() {
     this.dialog.show();
}

并尝试再次显示对话框(不起作用):

public void updateViewContext(UploadPicturesActivity activity) {
    this.context = activity;
    dialog.show();
}

此致

迈克尔

2 个答案:

答案 0 :(得分:2)

为什么不将属性android:configChanges="orientation"添加到AndroidManifest.xml文件中的活动声明。

android:configChanges属性的目的是防止在真正需要时重新创建活动。

screen orientation更改后,它不会忽略对话框。

Beginning with Android 3.2 (API level 13), the "screen size" also changes when the device 
switches between portrait and landscape orientation. Thus, if you want to prevent runtime 
restarts due to orientation change when developing for API level 13 or higher (as declared by the 
minSdkVersion and targetSdkVersion attributes), you must include the "screenSize" value in 
addition to the "orientation" value.That is, you must declare android:configChanges="orientation|screenSize"

答案 1 :(得分:1)

这是因为Android会破坏您的活动并在轮换时重新启动它。这意味着所有视图,对话框等都将被销毁。但是一个正在运行的线程不可能。对此最好的解决方案是在清单中为您的活动添加android:configChanges="orientation|screenSize",这会为您的活动关闭此行为。但是,只要您没有横向和纵向的不同布局,它仍会正确地重绘您的活动。