I have implemented the Asynctask+orientation change method by CommonsWare.
Basically, what it does, is that when device gets rotated, the activity gets destroyed. So in the final stage of the activity destroy, it detaches AsyncTask from activity and passes it to the new activity. When new activity is created I attach the AsyncTask back to the new activity.
Note: I didn't use the android:configChanges="orientation
in manifest, because I needed different layouts for portrait and landscape.
Everything works fine.
As we all know, there is a correct way to display dialogs and I'm using it.
This works fine also.
Problem occurs, when I try to use both those methods together.
My dialogs shows up when I call it with showDialog(n)
. If I rotate the device once, everything is ok. But when I rotate once more then after that logcat logs E/WindowManager(10035): ActivityMainActivity has leaked window DecorView@40520998 that was originally added here
but the application doesn't crash. After that, logcat starts logging the same error each time I rotate the device, but not crashing.
Code (main activity):
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);
}
}
}
Code (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
}
}