开发者

My app frequently throws android.view.WindowLeaked exception --

My app frequently throws exception like below:

E/WindowManager( 6282): android.view.WindowLeaked: Activity com.myActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4479b710 that was originally added here

The app shows a progress dialog when the main activity starts and starts a task. When the task is done, it will dismiss the progress dialog.

My code is like below. Can someone help me?

public class MyActivity extends Activity {

private static int ID_DIALOG_PROGRESS = 2001;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);        
    setContentView(R.layout.my_activity);
    showDialog(ID_DIALOG_PROGRESS);
    new MyTask().execute(null, null, null);
}

@Override
protected Dialog onCreateDialog(int id) {
    if (id == ID_DIALOG_PROGRESS) {
        ProgressDialog loadingDialog = new ProgressDialog(this);
        loadingDialog.setTitle("");
        loadingDialog.setMessage("");
        loadingDialog.setIndeterminate(true);
        loadingDialog.setCancelable(false);
        return loadingDialog;
    }

    return super.onCreateDialog(id);
}

private class MyTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... arg0) {

            /* Do something expensive here...*/

            /* Start other activity*/
            Intent intent = new Intent(MyActivity.this, OtherActivity.class);
            startActivityForResult(intent, 1000);
        }

        return null;
    }

    protected void onPostExecute(Void arg0) {
        dismissDialog(ID_DIALOG_PRO开发者_开发技巧GRESS);
    }
}
}

Most of the time, the exception was thrown from showDialog() call. The other time, the exception was thrown from dismissDialog() call.

Thank you in advance!


You're starting a new activity in doInBackground() before you dismiss the dialog in onPostExecute(), which is probably what is causing the dialog to leak. I would move

Intent intent = new Intent(MyActivity.this, OtherActivity.class);
startActivityForResult(intent, 1000);

to onPostExecute() after the dismissDialog() call and see what happens.


It's also good practise to place a try...catch around

dismissDialog(ID_DIALOG_PROGRESS);

Otherwise you will probably receive random application crashes when under some circumstances the dialog is not available anymore e.g. after screen rotation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜