Android: how to add view to WindowManager, and keep it floating at the top of my app all the time?

Anthonyeef picture Anthonyeef · Apr 26, 2017 · Viewed 9.2k times · Source

I need a view to show up at the top of my application, and when it's shown, it can keep showing at the top of all my application's other view(all the fragment and activity). It sounds like a Floating Action Button, but will always show at the top of my app.

I know I can do it via adding view to my phone's WindowManager, and hide it when I quit my app, show it again when I resume my app. This tricky method can work, but it also require some additional permission, which is I am trying to avoid.

If I only want to show in my app, can I achieve it without asking additional permission from user? If the answer is yes, then how? The key seems like some LayoutParams for the view, I tried but failed.

Would be nice if answer can show some detail code and explanation.

Answer

Abdul Kawee picture Abdul Kawee · Apr 26, 2017

You have to use WindowManager for this purpose

First add permission in manifest

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

Add image which you want to appear.

chatheadImg = (ImageView)chatheadView.findViewById(R.id.chathead_img);

Then make the service and add window manager to it.

WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
            PixelFormat.TRANSLUCENT);
    params.gravity = Gravity.TOP | Gravity.LEFT;
    params.x = 0;
    params.y = 100;

And just register touch events on view

chatheadView.setOnTouchListener(new View.OnTouchListener() {
@Override
        public boolean onTouch(View v, MotionEvent event) {
        Switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:

                      //To do
                    break;
                case MotionEvent.ACTION_MOVE:

                break;

});

check these tutorials for better understanding

http://www.androidhive.info/2016/11/android-floating-widget-like-facebook-chat-head/

https://github.com/henrychuangtw/Android-ChatHead