faizal
faizal

Reputation: 3565

Window leaked when exiting activity because of system overlay

I want to create an overlay that is visible all the time, over every other app. I use the below code on a button click in my activity

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);

It works, but it gives me an error when i exit the app :

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

How do i avoid this error?

Upvotes: 0

Views: 305

Answers (1)

faizal
faizal

Reputation: 3565

The trick is to use getApplicationContext().getSystemService(WINDOW_SERVICE).

When you simply use getSystemService(WINDOW_SERVICE), you are using the context of the activity. This context no longer exists when you exit the activity, so it will cause a window leaked error.

Upvotes: 1

Related Questions