阅读 2311

基于 EasyFloat 实现应用内全局悬浮窗

由于项目需求,需要实现一个应用内悬浮窗功能,要求是:

  • 点击悬浮窗图标可以跳转到一个固定的Activity A;
  • 用户在app内的任一activity里都能看到悬浮窗(除了Activity A)
  • 悬浮窗可以关闭,可以拖动,拖动过程中松手可以自动吸附到屏幕边缘。

经过搜索,我发现了一个第三方库EasyFloat(github.com/princekin-f… EasyFloat_intro.png

EasyFloat支持四种悬浮窗:

类型特点是否需要悬浮窗权限
CURRENT_ACTIVITY只在当前Activity显示
FOREGROUND仅应用前台时显示
BACKGROUND仅应用后台时显示
ALL_TIME一直显示(不分前后台)

那么问题来了,我要实现的功能是应用内的悬浮窗,回到桌面后没必要继续显示悬浮窗。所以我并不想申请悬浮窗权限。何况由于不同安卓手机系统的限制,悬浮窗权限没有一个统一的申请方式,需要针对不同手机系统做单独适配,测试起来也麻烦。

既然CURRENT_ACTIVITY不需要权限,那么有没有办法通过CURRENT_ACTIVITY 来实现应用内全局悬浮窗呢?

思路:

  1. 每打开一个activity,就创建一个CURRENT_ACTIVITY类型的悬浮窗,如果创建的速度足够快,用户会以为所有界面的悬浮窗都是同一个;
  2. 拖动悬浮窗后,记录下它的坐标。当跳转到别的activity时,将新创建的悬浮窗的位置设置成已保存的坐标。

经过测试,这个方案完全可行。以下是实现步骤:

1. 实现悬浮窗界面:

App.java:


public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        EasyFloat.init(this, true);

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
            }
            @Override
            public void onActivityStarted(@NonNull Activity activity) {
            }
            @Override
            public void onActivityResumed(@NonNull Activity activity) {
                doOnActivityResume(activity);
            }
            @Override
            public void onActivityPaused(@NonNull Activity activity) {
            }
            @Override
            public void onActivityStopped(@NonNull Activity activity) {
                doOnActivityStopped(activity);
            }
            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {
            }
            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {
            }
        });
    }

    private static final String TAG_FLOAT_VIEW = "TAG_FLOAT_VIEW";

    private void doOnActivityResume(Activity activity) {
        EasyFloat.Builder builder = EasyFloat.with(activity)
                .setLayout(R.layout.layout_float_window)
                .setShowPattern(ShowPattern.CURRENT_ACTIVITY) 
                .setAnimator(null) /*关闭动画*/
                .setSidePattern(SidePattern.RESULT_HORIZONTAL) /*吸附效果*/
                .setTag(TAG_FLOAT_VIEW);

        builder.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
        builder.show();
    }
    private void doOnActivityStopped(Activity activity) {
        EasyFloat.dismiss(activity, TAG_FLOAT_VIEW);//关闭前一个界面的悬浮窗
    }

}

复制代码

layout_float_window.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/bg_float_view">

    <TextView
        android:id="@+id/click_view_float"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="?attr/selectableItemBackgroundBorderless"
        android:clickable="true"
        android:gravity="center"
        android:text="点我"
        android:textColor="#fff"
        android:textSize="24sp">

    </TextView>

    <ImageView
        android:id="@+id/click_view_close"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@id/click_view_float"
        android:layout_alignParentTop="true"
        android:background="?attr/selectableItemBackgroundBorderless"
        android:clickable="true"
        android:padding="3dp"
        android:src="@drawable/ic_close_circle">

    </ImageView>

</RelativeLayout>
复制代码

实现效果:

效果1

期间遇到一个编译错误:

easyfloat的dismiss方法找不到

查询资料得知,这是由于EasyFloat是kotlin实现的,而我的工程是java开发的,根据 www.cnblogs.com/yubo0522/p/… ,加上kotlin相关支持即可。

2. 实现点击事件

    private static final String TAG_FLOAT_VIEW = "TAG_FLOAT_VIEW";

    private void doOnActivityResume(Activity activity) {
        //客服界面不弹出悬浮窗
        if (activity instanceof CustomerServiceActivity){
            return;
        }
        EasyFloat.Builder builder = EasyFloat.with(activity)
                .setLayout(R.layout.layout_float_window, new OnInvokeView() {
                    @Override
                    public void invoke(View view) {
                        View click_view_float = view.findViewById(R.id.click_view_float);
                        View click_view_close = view.findViewById(R.id.click_view_close);
                        click_view_float.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                CustomerServiceActivity.start(view.getContext());
                            }
                        });
                        click_view_close.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dismissFloatView(activity);
                            }
                        });
                    }
                })
                .setShowPattern(ShowPattern.CURRENT_ACTIVITY)
                .setAnimator(null)
                .setSidePattern(SidePattern.RESULT_HORIZONTAL)
                .setTag(TAG_FLOAT_VIEW);

        builder.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
        builder.show();
    }

    private void dismissFloatView(Activity activity) {
        EasyFloat.dismiss(activity, TAG_FLOAT_VIEW);
    }

    private void doOnActivityStopped(Activity activity) {
        dismissFloatView(activity);
    }
复制代码

效果图:

添加点击事件-效果图

3.拖动后记录位置

App.java:

public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        EasyFloat.init(this, true);

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
            }
            @Override
            public void onActivityStarted(@NonNull Activity activity) {
            }
            @Override
            public void onActivityResumed(@NonNull Activity activity) {
                doOnActivityResume(activity);
            }
            @Override
            public void onActivityPaused(@NonNull Activity activity) {
            }
            @Override
            public void onActivityStopped(@NonNull Activity activity) {
                doOnActivityStopped(activity);
            }
            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {
            }
            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {
            }
        });
    }

    private static final String TAG_FLOAT_VIEW = "TAG_FLOAT_VIEW";
    private static int floatXOffset;
    private static int floatYOffset;
    private static boolean hasDragged = false;
    private void doOnActivityResume(Activity activity) {
        //客服界面不弹出悬浮窗
        if (activity instanceof CustomerServiceActivity) {
            return;
        }
        EasyFloat.Builder builder = EasyFloat.with(activity)
                .setLayout(R.layout.layout_float_window, new OnInvokeView() {
                    @Override
                    public void invoke(View view) {
                        View click_view_float = view.findViewById(R.id.click_view_float);
                        View click_view_close = view.findViewById(R.id.click_view_close);
                        click_view_float.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                CustomerServiceActivity.start(view.getContext());
                            }
                        });
                        click_view_close.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dismissFloatView(activity);
                            }
                        });
                    }
                })
                .setShowPattern(ShowPattern.CURRENT_ACTIVITY)
                .setAnimator(null)
                .setSidePattern(SidePattern.RESULT_HORIZONTAL)
                .setTag(TAG_FLOAT_VIEW);

        if (!hasDragged) {
            builder.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
        } else {
            builder.setLocation(floatXOffset, floatYOffset);
        }

        builder.registerCallbacks(new OnFloatCallbacks() {
            @Override
            public void createdResult(boolean b, @org.jetbrains.annotations.Nullable String s, @org.jetbrains.annotations.Nullable View view) {
            }
            @Override
            public void show(@NotNull View view) {
            }
            @Override
            public void hide(@NotNull View view) {
            }
            @Override
            public void dismiss() {
            }
            @Override
            public void touchEvent(@NotNull View view, @NotNull MotionEvent motionEvent) {
            }
            @Override
            public void drag(@NotNull View view, @NotNull MotionEvent motionEvent) {
            }
            @Override
            public void dragEnd(@NotNull View view) {
                //拖动结束
                hasDragged = true;
                saveFloatViewPosition(activity);
            }
        });

        builder.show();
    }
    
    private void saveFloatViewPosition(Activity activity) {
        View floatView = EasyFloat.getFloatView(activity, TAG_FLOAT_VIEW);
        if (floatView != null) {
            //获取悬浮窗的位置
            int[] outLocation = new int[2];
            floatView.getLocationInWindow(outLocation);
            floatXOffset = outLocation[0];
            floatYOffset = outLocation[1] - Utils.getToolbarHeight(floatView.getContext()) - Utils.getStatusBarHeight(activity);
        }
    }

    private void dismissFloatView(Activity activity) {
        EasyFloat.dismiss(activity, TAG_FLOAT_VIEW);
    }

    private void doOnActivityStopped(Activity activity) {
        dismissFloatView(activity);
    }

}

复制代码

Utils.java:

public class Utils {
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }


    public static int getToolbarHeight(Context context) {

        TypedValue tv = new TypedValue();
        if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            int height = TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics());
            return height;
        }
        return 0;
    }

}

复制代码

最终实现效果:

记录悬浮窗的位置-效果图

完整源码地址: github.com/zty5678/InA…

文章分类
Android
文章标签