b15
b15

Reputation: 2351

Bringing a view to the absolute front (even over alert dialogs)

I need one view to always be at the forefront, even over alert dialogs. I figured there might be two ways to achieve this:

  1. Somehow create the alert dialog as part of an existing view, instead of being its own activity
  2. Some sort of flag on the view to bring it to the front of everything including alert dialogs

Is this possible? If so how?

Upvotes: 1

Views: 622

Answers (1)

rupinderjeet
rupinderjeet

Reputation: 2838

WindowManager with LayoutParams and Flag as TYPE_SYSTEM_ERROR. Shows over lockscreens too.

WindowManager windowManager = (WindowManager)getSystemService(WINDOW_SERVICE);

WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
PixelFormat.TRANSLUCENT);

params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 100; // position on screen (optional)
params.y = 100;

Add Views:

windowManager.addView(yourView, params);

Edit:

To avoid covering LockScreens: remove TYPE_SYSTEM_ERROR flag and add following:

WindowManager.LayoutParams.TYPE_PHONE

For this to work, you will need to add the following permission to your AndroidManifest.xml too:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

You don't need to request it at Runtime on most of devices except Android Marshmallow 6.0.0. There is a special way to request it than regular requests. It is checked using:

if (Settings.canDrawOverlays()) {
    // you have permission
} else {
    // send an intent with action "ACTION_MANAGE_OVERLAY_PERMISSION"
}

Upvotes: 1

Related Questions