欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Kotlin实现Android系统悬浮窗详解

程序员文章站 2022-06-17 22:23:29
目录android 弹窗浅谈系统悬浮窗具体实现权限申请代码设计具体实现floatwindowservice 类floatwindowmanager 类floatwindowmanager 类代码flo...

android 弹窗浅谈

我们知道 android 弹窗中,有一类弹窗会在应用之外也显示,这是因为他被申明成了系统弹窗,除此之外还有2类弹窗分别是:子弹窗应用弹窗

应用弹窗:就是我们常规使用的 dialog 之类弹窗,依赖于应用的 activity;子弹窗:依赖于父窗口,比如 popupwindow;系统弹窗:比如状态栏、toast等,本文所讲的系统悬浮窗就是系统弹窗。

系统悬浮窗具体实现

权限申请

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

代码设计

下面的包结构截图,简单展示了实现系统悬浮窗的代码结构,更复杂的业务需要可在此基础上进行扩展。

Kotlin实现Android系统悬浮窗详解

floatwindowservice:系统悬浮窗在此 service 中弹出;

floatwindowmanager:系统悬浮窗管理类;

floatlayout:系统悬浮窗布局;

homekeyobserverreceiver:

监听 home 键;

floatwindowutils:系统悬浮窗工具类。

具体实现

floatwindowservice 类

class floatwindowservice : service() {
 
    private val tag = floatwindowservice::class.java.simplename
    private var mfloatwindowmanager: floatwindowmanager? = null
    private var mhomekeyobserverreceiver: homekeyobserverreceiver? = null
 
    override fun oncreate() {
        tlogutils.i(tag, "oncreate: ")
        mfloatwindowmanager = floatwindowmanager(applicationcontext)
        mhomekeyobserverreceiver = homekeyobserverreceiver()
 
        registerreceiver(mhomekeyobserverreceiver, intentfilter(intent.action_close_system_dialogs))
        mfloatwindowmanager!!.createwindow()
    }
 
    override fun onbind(intent: intent?): ibinder? {
        return null
    }
 
    override fun onstartcommand(intent: intent?, flags: int, startid: int): int {
        return start_not_sticky
    }
 
    override fun ondestroy() {
        tlogutils.i(tag, "ondestroy: ")
        mfloatwindowmanager?.removewindow()
        if (mhomekeyobserverreceiver != null) {
            unregisterreceiver(mhomekeyobserverreceiver)
        }
    }
 
}

floatwindowmanager 类

包括系统悬浮窗的创建、显示、销毁(以及更新)。

 
public void addview(view view, viewgroup.layoutparams params); // 添加 view 到 window
public void updateviewlayout(view view, viewgroup.layoutparams params); //更新 view 在 window 中的位置
public void removeview(view view); //删除 view

floatwindowmanager 类代码

class floatwindowmanager constructor(context: context) {
 
    var isshowing = false
    private val tag = floatwindowmanager::class.java.simplename
    private var mcontext: context = context
    private var mfloatlayout = floatlayout(mcontext)
    private var mlayoutparams: windowmanager.layoutparams? = null
    private var mwindowmanager: windowmanager = context.getsystemservice(context.window_service) as windowmanager
 
    fun createwindow() {
        tlogutils.i(tag, "createwindow: start...")
        // 对象配置操作使用apply,额外的处理使用also
        mlayoutparams = windowmanager.layoutparams().apply {
            type = if (build.version.sdk_int >= build.version_codes.o) {
                // android 8.0以后需要使用type_application_overlay,不允许使用以下窗口类型来在其他应用和窗口上方显示提醒窗口:type_phone、type_priority_phone、type_system_alert、type_system_overlay、type_system_error。
                windowmanager.layoutparams.type_application_overlay
            } else {
                // 在android 8.0之前,悬浮窗口设置可以为type_phone,这种类型是用于提供用户交互操作的非应用窗口。
                // 在api level  = 23的时候,需要在android manifest.xml文件中声明权限system_alert_window才能在其他应用上绘制控件
                windowmanager.layoutparams.type_phone
            }
            // 设置图片格式,效果为背景透明
            format = pixelformat.rgba_8888
            // 设置浮动窗口不可聚焦(实现操作除浮动窗口外的其他可见窗口的操作)
            flags = windowmanager.layoutparams.flag_not_focusable
            // 调整悬浮窗显示的停靠位置为右侧置顶
            gravity = gravity.top or gravity.end
            width = 800
            height = 200
            x = 20
            y = 40
        }
 
        mwindowmanager.addview(mfloatlayout, mlayoutparams)
        tlogutils.i(tag, "createwindow: end...")
        isshowing = true
    }
 
    fun showwindow() {
        tlogutils.i(tag, "showwindow: isshowing = $isshowing")
        if (!isshowing) {
            if (mlayoutparams == null) {
                createwindow()
            } else {
                mwindowmanager.addview(mfloatlayout, mlayoutparams)
                isshowing = true
            }
        }
    }
 
    fun removewindow() {
        tlogutils.i(tag, "removewindow: isshowing = $isshowing")
        mwindowmanager.removeview(mfloatlayout)
        isshowing = false
    }
 
}

floatlayout 类及其 layout

系统悬浮窗自定义view:floatlayout

class floatlayout @jvmoverloads constructor(context: context, attrs: attributeset? = null, defstyleattr: int = 0, defstyleres: int = 0) :
    constraintlayout(context, attrs, defstyleattr, defstyleres) {
 
    private var mtime: tcltextview
    private var mdistance: tcltextview
    private var mspeed: tcltextview
    private var mcalories: tcltextview
 
    init {
        val view = layoutinflater.from(context).inflate(r.layout.do_exercise_view_float_layout, this, true)
        mtime = view.findviewbyid(r.id.float_layout_tv_time)
        mdistance = view.findviewbyid(r.id.float_layout_tv_distance)
        mspeed = view.findviewbyid(r.id.float_layout_tv_speed)
        mcalories = view.findviewbyid(r.id.float_layout_tv_calories)
    }
 
}

布局文件:float_layout_tv_time

homekeyobserverreceiver 类

class homekeyobserverreceiver : broadcastreceiver() {
 
    override fun onreceive(context: context?, intent: intent?) {
        try {
            val action = intent!!.action
            val reason = intent.getstringextra("reason")
            tlogutils.d(tag, "homekeyobserverreceiver: action = $action,reason = $reason")
            if (intent.action_close_system_dialogs == action && "homekey" == reason) {
                val keycode = intent.getintextra("keycode", keyevent.keycode_unknown)
                tlogutils.d(tag, "keycode = $keycode")
                context?.stopservice(intent(context, floatwindowservice::class.java))
            }
        } catch (ex: exception) {
            ex.printstacktrace()
        }
    }
 
    companion object {
        private val tag = homekeyobserverreceiver::class.java.simplename
    }
 
}

floatwindowutils 类

object floatwindowutils {
 
    const val request_float_code = 1000
    private val tag = floatwindowutils::class.java.simplename
 
    /**
     * 判断service是否开启
     */
    fun isservicerunning(context: context, servicename: string): boolean {
        if (textutils.isempty(servicename)) {
            return false
        }
        val mymanager = context.getsystemservice(context.activity_service) as activitymanager
        val runningservice = mymanager.getrunningservices(1000) as arraylist<activitymanager.runningserviceinfo>
        runningservice.foreach {
            if (it.service.classname == servicename) {
                return true
            }
        }
        return false
    }
 
    /**
     * 检查悬浮窗权限是否开启
     */
    @suppresslint("newapi")
    fun checksuspendedwindowpermission(context: activity, block: () -> unit) {
        if (commonrompermissioncheck(context)) {
            block()
        } else {
            toast.maketext(context, "请开启悬浮窗权限", toast.length_short).show()
            context.startactivityforresult(intent(settings.action_manage_overlay_permission).apply {
                data = uri.parse("package:${context.packagename}")
            }, request_float_code)
        }
    }
 
    /**
     * 判断悬浮窗权限权限
     */
    fun commonrompermissioncheck(context: context?): boolean {
        var result = true
        if (build.version.sdk_int >= 23) {
            try {
                val clazz: class<*> = settings::class.java
                val candrawoverlays = clazz.getdeclaredmethod("candrawoverlays", context::class.java)
                result = candrawoverlays.invoke(null, context) as boolean
            } catch (e: exception) {
                tlogutils.e(tag, e)
            }
        }
        return result
    }
 
}

总结

本文并未详细讨论系统悬浮窗的拖动功能,实现系统悬浮穿基本功能可以总结为以下几个步骤:

1. 声明及申请权限;
2. 构建悬浮窗需要的控件 service、receiver、manager、layout、util;
3. 使用 windowmanager 创建、显示、销毁(以及更新)layout。

到此这篇关于kotlin实现android系统悬浮窗详解的文章就介绍到这了,更多相关android kotlin系统悬浮窗内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: Android Kotlin