android.view.WindowLeaked exception

。_饼干妹妹 提交于 2019-12-04 04:08:27

When a dialog on an activity is set to visible but on orientation changes the activity itself is destroyed, then it causes leaked window error.

There are two methods to handle this situation:-

Method 1
Therefore,you need to dismiss dialog in activity's onStop or onDestroy method. For example:

@Override
protected void onStop() {
    super.onStop();

    if(pd!= null)
        pd.dismiss();
}

and define dialog in activity class

ProgressDialog pd;

This link will help you Handling progress dialogs and orientation changes

Method 2
You have to add this to the activity declaration in the manifest:

android:configChanges="orientation"

so it looks like

<activity android:label="@string/app_name" 
        android:configChanges="orientation|keyboardHidden" 
        android:name="com.eisuru.abc.MainActivity">

The matter is that the system destroys the activity when a change in the configuration occurs. See ConfigurationChanges.

So putting that in the configuration file avoids the system to destroy your activity. Instead it invokes the onConfigurationChanged(Configuration) method.

You're trying to show a Dialog after you've exited an Activity.

The solution is to call dismiss() on the Dialog you created in Example.java:183 before exiting the Activity, e.g. in onPause(). All windows&dialogs should be closed before leaving an Activity.

Or

Add this to your manifest:

android:configChanges="orientation|keyboardHidden

Then in your activity add this somewhere:

 @Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
{
    Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
  //ur Code
}
 if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
{
    Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    //ur Code
} 
}

dialog is a child that are belong to main thread and if you want to show or kill them you must do this on OnUiThread like this. I am using fragment and when I show dialog, get this exception. But this method save me.

 getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            pDialog.show();//dismiss any dialog like this
        }
    });

I got this error because I was adding a view in the onResume() of all my activities using WindowManager.addView(). To solve the problem I had to call WindowManager.removeView() in the onPause() of all my activities.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!