由于系统覆盖,退出活动时窗口泄露

时间:2014-07-08 04:17:01

标签: android

我想创建一个始终可见的叠加层,覆盖其他所有应用。我在活动中单击按钮时使用以下代码

WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
                PixelFormat.TRANSLUCENT
                );
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
windowManager.addView(myViewGroup, params);

它可以工作,但是当我退出应用程序时它会给我一个错误:

E/WindowManager(17254): android.view.WindowLeaked: 
Activity com.myPackage.myApp.MainActivity has leaked window
com.myPackage.myApp.MainActivity$myViewGroup{4269d670 V.E..... ........ 0,0-1024,1024} 
that was originally added here

如何避免此错误?

1 个答案:

答案 0 :(得分:1)

诀窍是使用getApplicationContext().getSystemService(WINDOW_SERVICE)

当您只使用getSystemService(WINDOW_SERVICE)时,您正在使用活动的上下文。退出活动时,此上下文不再存在,因此会导致窗口泄露错误。