Xamarin Android - System Overlay (Always On Top)

I am trying to create an image that stays on top of all windows in Android using Xamarin Android (not xamarin forms). After searching around the internet for a few days I got the code to work... kinda. The below code will take my app icon and put it overtop any window. It allows for interaction with the keyboard. This is successfully running on my Android 5.0 version phone. After executing the code, my app icon will be on top of all windows. I can navigate to the home screen, lock the phone, ect... it is always on top. Great.

But when I try it on a device with Android 4.1 (or earlier), it does not not work correctly. Executing this code will show the app icon on top of my application, but when I navigate to a different window (or hit the home button), it will just show the homescreen without any icons or without my overlay. I can swipe to different pages of my homescreen, but there are never any icons that show up and the only way to do anything on the device is to close my application. I'm not sure what I am missing to help support the older versions of android OS. I have installed other apps that do this on the devices and they work correctly. Any suggestions? Thank you in advance!

    ImageView overlayImage = new ImageView(this);
    overlayImage.SetImageResource(Resource.Drawable.Icon);

    var param = new WindowManagerLayoutParams(
                    ViewGroup.LayoutParams.MatchParent,
                    ViewGroup.LayoutParams.MatchParent,
                    WindowManagerTypes.SystemOverlay,
                    WindowManagerFlags.Fullscreen | WindowManagerFlags.WatchOutsideTouch | WindowManagerFlags.AllowLockWhileScreenOn | WindowManagerFlags.NotTouchable | WindowManagerFlags.NotFocusable,
                    Android.Graphics.Format.Translucent);

    param.Gravity = GravityFlags.Top;

    overlayImage.SetScaleType(ImageView.ScaleType.FitXy);

    IWindowManager windowManager = GetSystemService(WindowService).JavaCast<IWindowManager>();
    windowManager.AddView(overlayImage, param);

I've also added this to my manifest:

uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"

Any help will be very helpful!

Answers

  • Just wanted to say thank you for your code! It's a great start and for what I was looking for. Now I just need to make the image clickable.

Sign In or Register to comment.