如何修复 Android 应用程序泄漏的资源

How to fix Android application leaked resources

我的 Activity 中有以下代码:-

public void showPopup(View view) {
    View popupView = getLayoutInflater().inflate(R.layout.popup_layout, null);
    PopupWindow popupWindow = new PopupWindow(popupView,
            WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
    // Example: If you have a TextView inside `popup_layout.xml`
    ImageView imageView = (ImageView) popupView.findViewById(R.id.popupImageView);
    if (mImagePath != null) {
        if (Utility.fileExist(mImagePath)) {
            imageView.setImageBitmap(BitmapFactory.decodeFile(mImagePath));
        } else {
            Toast.makeText(this, "Image not found!", Toast.LENGTH_LONG).show();
        }
    } else {
        Toast.makeText(this, "Image not found!", Toast.LENGTH_LONG).show();
    }

    popupWindow.setFocusable(true);

    popupWindow.setBackgroundDrawable(new ColorDrawable());
    int location[] = new int[2];

    view.getLocationOnScreen(location);

    popupWindow.showAtLocation(view, Gravity.NO_GRAVITY,
            location[0], location[1] + view.getHeight());
}

屏幕旋转时出现以下错误。您能否告知如何解决此错误:-

08-13 16:04:08.358  20827-20827/com.app.locationnote E/WindowManager﹕ Activity com.app.locationnote.NoteEditor has leaked window android.widget.PopupWindow$PopupViewContainer@4274ad80 that was originally added here
android.view.WindowLeaked: Activity com.masum.locationnote.NoteEditor has leaked window android.widget.PopupWindow$PopupViewContainer@4274ad80 that was originally added here
        at android.view.ViewRootImpl.<init>(ViewRootImpl.java:403)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:311)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
        at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
        at android.view.Window$LocalWindowManager.addView(Window.java:554)

一种方法是使用 LeakCanary 自动检测泄漏。另外,请确保在暂停或销毁 Activity 时在 PopupWindow 上调用 dismiss()。

您可以在 Activity.onDestroy() 方法中关闭弹出窗口:

 if (popupWindow.isShowing()) {
     popupWindow.dismiss();
}