我已經實現了Asynctask+orientation change method by CommonsWare。即使我使用onCreateDialog和onShowDialog也會漏出窗口
基本上,它的作用是當設備旋轉時,活動被破壞。因此,在活動銷燬的最後階段,它將AsyncTask從活動中分離出來,並將其傳遞給新活動。當創建新活動時,我將AsyncTask附加到新活動。
注意:我沒有在清單中使用android:configChanges="orientation
,因爲我需要不同的肖像和風景佈局。
一切工作正常。
衆所周知,有一個correct way to display dialogs,我正在使用它。
這工作正常。
問題發生時,當我嘗試使用這兩種方法在一起。
當我用showDialog(n)
調用它時,出現對話框。如果我旋轉設備一次,一切都很好。但是當我再一次旋轉後,logcat日誌E/WindowManager(10035): ActivityMainActivity has leaked window [email protected] that was originally added here
但應用程序不會崩潰。之後,logcat每次旋轉設備時都會記錄相同的錯誤,但不會崩潰。
代碼(主要活動):
public class MainActivity extends BaseActivity {
private static final int RATE_US = 1;
private MainPageAsync task = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showDialog(RATE_US);
task = (MainPageAsync) getLastNonConfigurationInstance();
if (task == null) {
task = new MainPageAsync(this);
task.execute(super.currentPage);
} else {
task.attach(this);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
// remove activity from asynctask
if (task != null)
task.detach();
return task;
}
@Override
protected Dialog onCreateDialog(int id) {
if (id == RATE_US) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("test")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
//dosomethinghere
}
});
return builder.create();
} else {
return super.onCreateDialog(id);
}
}
}
碼(的AsyncTask):
public class MainPageAsync extends AsyncTask<String, String, Document> {
private MainActivity a;
public MainPageAsync(MainActivity activity) {
this.a = activity;
}
public void detach() {
a = null;
}
public void attach(MainActivity activity) {
this.a = activity;
}
@Override
protected Document doInBackground(String... params) {
//network work
}
@Override
protected void onPostExecute(final Document doc) {
//more work on UI thread
}
}
觀察:它看起來像問題連接到我調用'showDialog'的地方。當我在'onCreate'中執行操作時,我一直在旋轉時收到泄露的窗口異常,但是當我通過菜單按鈕執行操作時,它看起來並不像它產生的異常... – 2012-03-12 16:59:01