我使用ACRA报告应用程序崩溃。我得到了一个视图没有附加到窗口管理器错误消息,并认为我已经通过包装pDialog.dismiss()修复了它;在if语句中:

if (pDialog!=null) 
{
    if (pDialog.isShowing()) 
    {
        pDialog.dismiss();   
    }
}

它减少了我收到的未附加到窗口管理器崩溃的视图数量,但我仍然得到一些,我不确定如何解决它。

错误信息:

java.lang.IllegalArgumentException: View not attached to window manager
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:425)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:327)
at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:83)
at android.app.Dialog.dismissDialog(Dialog.java:330)
at android.app.Dialog.dismiss(Dialog.java:312)
at com.package.class$LoadAllProducts.onPostExecute(class.java:624)
at com.package.class$LoadAllProducts.onPostExecute(class.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)

代码片段:

class LoadAllProducts extends AsyncTask<String, String, String> 
{

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() 
    {
        super.onPreExecute();
        pDialog = new ProgressDialog(CLASS.this);
        pDialog.setMessage("Loading. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) 
    {
        // Building Parameters
        doMoreStuff("internet");
        return null;
    }


    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) 
    {
         // dismiss the dialog after getting all products
         if (pDialog!=null) 
         {
                if (pDialog.isShowing()) 
                {
                    pDialog.dismiss();   //This is line 624!    
                }
         }
         something(note);
    }
}

清单:

    <activity
        android:name="pagename.CLASS" 
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout"            
        android:label="@string/name" >
    </activity>

为了阻止撞车,我错过了什么?


如何重现错误:

在您的设备上启用此选项:设置->开发人员选项->不要保留活动。 当AsyncTask正在执行并且ProgressDialog正在显示时,按Home键。

Android操作系统会在活动被隐藏时立即销毁它。当onPostExecute被调用时,Activity将处于“完成”状态,并且ProgressDialog不会附加到Activity。

如何解决:

在onPostExecute方法中检查活动状态。 取消onDestroy方法中的ProgressDialog。否则,将抛出android.view. windowleaks异常。此异常通常来自活动结束时仍处于活动状态的对话框。

试试这个固定的代码:

public class YourActivity extends Activity {

    private void showProgressDialog() {
        if (pDialog == null) {
            pDialog = new ProgressDialog(StartActivity.this);
            pDialog.setMessage("Loading. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
        }
        pDialog.show();
    }

    private void dismissProgressDialog() {
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        dismissProgressDialog();
        super.onDestroy();
    }

    class LoadAllProducts extends AsyncTask<String, String, String> {

        // Before starting background thread Show Progress Dialog
        @Override
        protected void onPreExecute() {
            showProgressDialog();
        }

        //getting All products from url
        protected String doInBackground(String... args) {
            doMoreStuff("internet");
            return null;
        }

        // After completing background task Dismiss the progress dialog
        protected void onPostExecute(String file_url) {
            if (YourActivity.this.isDestroyed()) { // or call isFinishing() if min sdk version < 17
                return;
            }
            dismissProgressDialog();
            something(note);
        }
    }
}

重写onConfigurationChanged并取消进度对话框。 如果进度对话框在纵向中创建,并在横向中解散,那么它将抛出未附加到窗口管理器的视图错误。

同时在onPause(), onBackPressed和onDestroy方法中停止进度条和异步任务。

if(asyncTaskObj !=null && asyncTaskObj.getStatus().equals(AsyncTask.Status.RUNNING)){

    asyncTaskObj.cancel(true);

}

看看准则是如何运作的:

调用异步任务后,异步任务将在后台运行。这是可取的。现在,这个异步任务有一个附加到Activity的进度对话框,如果你问如何查看代码:

pDialog = new ProgressDialog(CLASS.this);

你通过考试了。这是论点的背景。因此Progress对话框仍然附加到活动。

现在考虑一下这个场景: 如果我们尝试使用finish()方法完成活动,当异步任务正在进行时,是您试图访问附加到活动的资源的点,即活动不再存在时的进度条。

因此你得到:

java.lang.IllegalArgumentException: View not attached to the window manager

解决方法:

1)确保对话框在活动结束前被解除或取消。

2)完成活动,只有在对话框被解散后,即异步任务结束。


问题可能是活动已经完成或正在完成。

添加一个检查isfinished,并仅在此为false时解散对话框

if (!YourActivity.this.isFinishing() && pDialog != null) {
    pDialog.dismiss();
}

isfinished:检查该活动是否正在完成,要么是因为您调用了finish,要么是因为其他人要求它完成。


@Override
public void onPause() {
    super.onPause();

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

提到这一点。


这个问题是因为你的活动在调用dismiss函数之前完成了。处理异常,并检查您的ADB日志的确切原因。

/**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
    try {
         if (pDialog!=null) {
            pDialog.dismiss();   //This is line 624!    
         }
    } catch (Exception e) {
        // do nothing
    }
     something(note);
}

基于@erakitin的答案,但也兼容Android版本< API级别17。不幸的是,Activity.isDestroyed()只支持API级别17以后,所以如果你的目标是一个更老的API级别,就像我一样,你必须自己检查它。还没有得到视图没有附加到窗口管理器异常之后。

示例代码

public class MainActivity extends Activity {
    private TestAsyncTask mAsyncTask;
    private ProgressDialog mProgressDialog;
    private boolean mIsDestroyed;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (condition) {
            mAsyncTask = new TestAsyncTask();
            mAsyncTask.execute();
        }
    }

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

        if (mAsyncTask != null && mAsyncTask.getStatus() != AsyncTask.Status.FINISHED) {
            Toast.makeText(this, "Still loading", Toast.LENGTH_LONG).show();
            return;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mIsDestroyed = true;

        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    public class TestAsyncTask extends AsyncTask<Void, Void, AsyncResult> {    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog = ProgressDialog.show(MainActivity.this, "Please wait", "doing stuff..");
        }

        @Override
        protected AsyncResult doInBackground(Void... arg0) {
            // Do long running background stuff
            return null;
        }

        @Override
        protected void onPostExecute(AsyncResult result) {
            // Use MainActivity.this.isDestroyed() when targeting API level 17 or higher
            if (mIsDestroyed)// Activity not there anymore
                return;

            mProgressDialog.dismiss();
            // Handle rest onPostExecute
        }
    }
}

覆盖onDestroy的活动和解散你的对话框,使其为空

protected void onDestroy ()
    {
        if(mProgressDialog != null)
            if(mProgressDialog.isShowing())
                mProgressDialog.dismiss();
        mProgressDialog= null;
    }

我有办法重现这个异常。 我使用2 AsyncTask。一个人做长任务,另一个人做短任务。在短任务完成后,调用finish()。当长任务完成并调用Dialog.dismiss()时,它崩溃了。 下面是我的示例代码:

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(TAG, "onCreate");

        new AsyncTask<Void, Void, Void>(){
            @Override
            protected void onPreExecute() {
                mProgressDialog = ProgressDialog.show(MainActivity.this, "", "plz wait...", true);
            }

            @Override
            protected Void doInBackground(Void... nothing) {
                try {
                    Log.d(TAG, "long thread doInBackground");
                    Thread.sleep(20000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                Log.d(TAG, "long thread onPostExecute");
                if (mProgressDialog != null && mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                    mProgressDialog = null;
                }
                Log.d(TAG, "long thread onPostExecute call dismiss");
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

        new AsyncTask<Void, Void, Void>(){
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    Log.d(TAG, "short thread doInBackground");
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                Log.d(TAG, "short thread onPostExecute");
                finish();
                Log.d(TAG, "short thread onPostExecute call finish");
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
    }
}

您可以尝试这样做,并找出解决此问题的最佳方法。 根据我的研究,至少有4种方法可以解决这个问题:

@erakitin的回答:调用isFinishing()来检查活动的状态 @Kapé的回答是:设置flag来检查活动的状态 使用try/catch来处理它。 调用onDestroy()中的AsyncTask.cancel(false)。它将阻止asynctask执行onPostExecute(),而是执行onCancelled()。 注意:onPostExecute()仍然会执行,即使你调用AsyncTask.cancel(false)在旧的Android操作系统,如Android 2.X.X。

你可以选择最适合你的。


最佳解决方案。检查第一个上下文是活动上下文还是应用程序上下文 如果活动上下文只检查活动是否完成,则调用dialog.show()或dialog.dismiss();

参见下面的示例代码…希望对大家有所帮助! 显示对话框

if (context instanceof Activity) {
   if (!((Activity) context).isFinishing())
     dialog.show();
}

把对话框

if (context instanceof Activity) {
       if (!((Activity) context).isFinishing())
         dialog.dismiss();
    }

如果你想添加更多的检查,那么使用&&条件添加dialog. isshows()或dialog !-null。


对于在片段中创建的对话框,我使用以下代码:

ProgressDialog myDialog = new ProgressDialog(getActivity());
myDialog.setOwnerActivity(getActivity());
...
Activity activity = myDialog.getOwnerActivity();
if( activity!=null && !activity.isFinishing()) {
    myDialog.dismiss();
}

我使用这种模式来处理片段可能从活动中分离的情况。


可能你全局初始化pDialog,然后删除它并在本地初始化你的视图或对话框。我有同样的问题,我已经这样做了,我的问题已经解决了。希望这对你有用。


首先,崩溃的原因是decorView的索引是-1,我们可以从Android源代码中知道,有代码片段:

类:android.view.WindowManagerGlobal 文件:WindowManagerGlobal.java

private int findViewLocked(View view, boolean required) {
        final int index = mViews.indexOf(view);
//here, view is decorView,comment by OF
        if (required && index < 0) {
            throw new IllegalArgumentException("View=" + view + " not attached to window manager");
        }
        return index;
    }

所以我们得到了跟随分辨率,只是判断decorView的索引,如果它大于0,那么继续,或者只是返回并放弃解散,代码如下:

try {
            Class<?> windowMgrGloable = Class.forName("android.view.WindowManagerGlobal");
            try {
                Method mtdGetIntance = windowMgrGloable.getDeclaredMethod("getInstance");
                mtdGetIntance.setAccessible(true);
                try {
                    Object windownGlobal = mtdGetIntance.invoke(null,null);
                    try {
                        Field mViewField = windowMgrGloable.getDeclaredField("mViews");
                        mViewField.setAccessible(true);
                        ArrayList<View> mViews = (ArrayList<View>) mViewField.get(windownGlobal);
                        int decorViewIndex = mViews.indexOf(pd.getWindow().getDecorView());
                        Log.i(TAG,"check index:"+decorViewIndex);
                        if (decorViewIndex < 0) {
                            return;
                        }
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        if (pd.isShowing()) {
            pd.dismiss();
        }

我们还在onPause方法或onDestroy方法上解散了对话框

@Override
protected void onPause() {
    super.onPause();
    dialog.dismiss();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    dialog.dismiss();
}

重写dismiss()方法,如下所示:

@Override
public void dismiss() {
    Window window = getWindow();
    if (window == null) {
        return;
    }
    View decor = window.getDecorView();
    if (decor != null && decor.getParent() != null) {
        super.dismiss();
    }
}

要重现问题,只需在解散对话框之前完成活动。


您可以尝试检查这个解决方案或尝试下面的解决方案。

if (pDialog instanceof Activity && !((Activity) mContext).isFinishing())
        pDialog.show();

检查所有者活动是否仍然存在:

if (dialog.getOwnerActivity() ==null || dialog.getOwnerActivity().isFinishing()) {
    dialog.dismiss();
}

我使用这个简单的扩展函数来检查活动是否被销毁。

    protected fun Activity?.isNoMore(): Boolean {
        return this?.let {
            isFinishing || isDestroyed
        } ?: true
    }

在下面提到的活动中使用它。

if (!isNoMore()) {
//show your dialog. Also, make the null check for dialog object.
}

上面的解决方案都不适合我,因为我使用自定义对话类,我不想覆盖停止/销毁方法在我所有的活动,更容易添加一个参数到我的类,并从实例发送它,这个解决方案适合我

class CustomLoadingClass(var activity: Activity?, var lifecycle: Lifecycle? = null) {

lateinit var dialog: Dialog

fun show(cancelable: Boolean = false, title: String? = null) {
    lifecycle?.let {
        val defaultLifecycleObserver = object : DefaultLifecycleObserver {
            override fun onCreate(owner: LifecycleOwner) {
                super.onCreate(owner)
                activity?.let { it ->
                    if (!it.isFinishing && !it.isDestroyed) {
                        dialog = Dialog(it, android.R.style.Theme_Translucent_NoTitleBar)
                        dialog.setContentView(it.layoutInflater.inflate(R.layout.full_screen_progress_bar,null)!!)
                        dialog.setCancelable(cancelable)
                        dialog.show()
                    }
                }
            }
            override fun onPause(owner: LifecycleOwner) {
                super.onPause(owner)
                dismiss()
            }

            override fun onStop(owner: LifecycleOwner) {
                super.onStop(owner)
                dismiss()
            }

            override fun onDestroy(owner: LifecycleOwner) {
                super.onDestroy(owner)
                dismiss()
            }
        }
        it.addObserver(defaultLifecycleObserver)
    }
}

fun dismiss() {
    activity?.let { it ->
         if (!it.isFinishing && !it.isDestroyed) 
           dialog.dismiss()
    }
  }
}