Android 监听框架开发教程 蓝牙状态监听例子 kotlin

前言

有些时候,我们需要在某些Activity中监听某些状态。当然不可能在每个Activity中创建一个实例去查询和绑定吧。这时候,就需要一个统一管理状态的框架,下面就以蓝牙状态监听为例,描述如何开发一个监听框架。

文件架构

在这里插入图片描述

代码

监听者注解

创建文件 RDBluetoothObserver ,注解类,用于描述监听者的方法

/**
 * 蓝牙状态观察者注解
 *
 * @author D10NG
 * @date on 2019-11-12 09:25
 */
@kotlin.annotation.Target(AnnotationTarget.FUNCTION)
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
annotation class RDBluetoothObserver

状态值枚举类

创建文件 RDBluetoothStatus

/**
 * 蓝牙开关状态
 *
 * @author D10NG
 * @date on 2019-11-12 09:27
 */
enum class RDBluetoothStatus(val msg: String) {

    NONE(msg = "当前设备不支持蓝牙BLE"),
    STATE_TURNING_ON(msg = "正在打开蓝牙"),
    STATE_ON(msg = "蓝牙已打开"),
    STATE_TURNING_OFF(msg = "正在关闭蓝牙"),
    STATE_OFF(msg = "蓝牙已关闭"),
    CONNECTED(msg = "蓝牙已连接"),
    DISCONNECTED(msg = "蓝牙已断开连接")

}

编写接口

创建文件 IBluetoothCallBack

/**
 * 蓝牙状态接口
 *
 * @author D10NG
 * @date on 2019-11-12 09:30
 */
interface IBluetoothCallBack {

    /**
     * 注册
     * @param obj
     */
    fun register(obj: Any)

    /**
     * 取消注册
     * @param obj
     */
    fun unRegister(obj: Any)

    /**
     * 取消注册
     */
    fun unRegisterAll()

    /**
     * 打开蓝牙
     */
    fun openBluetooth()

    /**
     * 关闭蓝牙
     */
    fun closeBluetooth()

    /**
     * 获取蓝牙状态
     * @return
     */
    fun getBluetoothStatus() : RDBluetoothStatus
}

业务逻辑

创建文件 BluetoothCallBack

/**
 * 蓝牙状态监听
 *
 * @author D10NG
 * @date on 2019-11-12 09:31
 */
class BluetoothCallBack constructor(
    application: Application
) : IBluetoothCallBack {

    // 观察者,key=类、value=方法
    private val checkManMap = HashMap<Any, Method>()

    @Volatile
    private var bluetoothStatus: RDBluetoothStatus

    private val bluetoothReceiver = BluetoothReceiver()

    init {
        // 初始化广播
        val intentFilter = IntentFilter()
        // 监视蓝牙关闭和打开的状态
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED)
        // 开始监听
        application.registerReceiver(bluetoothReceiver, intentFilter)

        // 初始化蓝牙状态
        val bleManager = application.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        val adapter = bleManager.adapter
        bluetoothStatus = when {
            adapter == null -> RDBluetoothStatus.NONE
            adapter.isEnabled -> RDBluetoothStatus.STATE_ON
            else -> RDBluetoothStatus.STATE_OFF
        }
    }

    override fun register(obj: Any) {
        val clz = obj.javaClass
        if (!checkManMap.containsKey(clz)) {
            val method = AnnotationUtils.findAnnotationMethod(
                clz, RDBluetoothObserver::class.java,
                RDBluetoothStatus::class.java) ?: return
            checkManMap[obj] = method
        }
    }

    override fun unRegister(obj: Any) {
        checkManMap.remove(obj)
    }

    override fun unRegisterAll() {
        checkManMap.clear()
    }

    override fun openBluetooth() {
        val ble = BluetoothAdapter.getDefaultAdapter()
        ble?.enable()
    }

    override fun closeBluetooth() {
        val ble = BluetoothAdapter.getDefaultAdapter()
        ble?.disable()
    }

    override fun getBluetoothStatus(): RDBluetoothStatus = bluetoothStatus

    // 执行
    private fun post(status: RDBluetoothStatus) {
        bluetoothStatus = status
        val set: Set<Any> = checkManMap.keys
        for (obj in set) {
            val method = checkManMap[obj] ?: continue
            method.invoke(obj, status)
        }
    }

    inner class BluetoothReceiver : BroadcastReceiver() {

        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent?.action ?: return
            when (action) {
                BluetoothAdapter.ACTION_STATE_CHANGED -> {
                    when(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0)) {
                        BluetoothAdapter.STATE_TURNING_ON -> post(RDBluetoothStatus.STATE_TURNING_ON)
                        BluetoothAdapter.STATE_ON -> post(RDBluetoothStatus.STATE_ON)
                        BluetoothAdapter.STATE_TURNING_OFF -> post(RDBluetoothStatus.STATE_TURNING_OFF)
                        BluetoothAdapter.STATE_OFF -> post(RDBluetoothStatus.STATE_OFF)
                    }
                }
                BluetoothDevice.ACTION_ACL_CONNECTED -> {
                    post(RDBluetoothStatus.CONNECTED)
                }
                BluetoothDevice.ACTION_ACL_DISCONNECTED -> {
                    post(RDBluetoothStatus.DISCONNECTED)
                }
            }
        }
    }
}

暴露接口 单例

创建文件 RDBluetoothManager

/**
 * 蓝牙管理器
 *
 * @author D10NG
 * @date on 2019-11-12 09:24
 */
class RDBluetoothManager constructor(
    application: Application
) : IBluetoothCallBack {

    private val bluetoothCallBack : IBluetoothCallBack

    companion object {

        @Volatile
        private var INSTANCE : RDBluetoothManager? = null

        @JvmStatic
        fun getInstance(application: Application) : RDBluetoothManager {
            val temp = INSTANCE
            if (null != temp) {
                return temp
            }
            synchronized(this) {
                val instance = RDBluetoothManager(application)
                INSTANCE = instance
                return instance
            }
        }
    }

    init {
        bluetoothCallBack = BluetoothCallBack(application)
    }

    override fun register(obj: Any) {
        bluetoothCallBack.register(obj)
    }

    override fun unRegister(obj: Any) {
        bluetoothCallBack.unRegister(obj)
    }

    override fun unRegisterAll() {
        bluetoothCallBack.unRegisterAll()
    }

    override fun openBluetooth() {
        bluetoothCallBack.openBluetooth()
    }

    override fun closeBluetooth() {
        bluetoothCallBack.closeBluetooth()
    }

    override fun getBluetoothStatus(): RDBluetoothStatus = bluetoothCallBack.getBluetoothStatus()

}

混淆封装

如果你想打包成第三方库的话,看我的另一篇文章:
Android 简单开发sdk教程一 接口写法和混淆规则

Github

DL10BluetoothListener

完事

以下是 Kotlin 代码示例,用于检测 WiFi 连接状态的更改: ```kotlin import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.net.NetworkInfo import android.net.NetworkRequest import android.net.wifi.WifiInfo import android.net.wifi.WifiManager import android.os.Build import android.util.Log class WifiStateReceiver : BroadcastReceiver() { private var wifiManager: WifiManager? = null private var connectivityManager: ConnectivityManager? = null private var networkCallback: ConnectivityManager.NetworkCallback? = null override fun onReceive(context: Context, intent: Intent) { wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager if (wifiManager?.isWifiEnabled == true) { Log.d(TAG, "WiFi is enabled.") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { networkCallback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: android.net.Network) { super.onAvailable(network) Log.d(TAG, "WiFi is connected.") } override fun onLost(network: android.net.Network) { super.onLost(network) Log.d(TAG, "WiFi is disconnected.") } } val builder = NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) connectivityManager?.registerNetworkCallback(builder.build(), networkCallback!!) } else { context.registerReceiver(this, IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION)) } } else { Log.d(TAG, "WiFi is disabled.") } } companion object { private const val TAG = "WifiStateReceiver" } } ``` 在 `onReceive()` 方法中,我们检查 WiFi 是否已启用。如果是,则根据设备的 Android 版本注册网络回调或广播接收器以监听网络状态更改。 如果 Android 版本大于或等于 N,我们将创建一个 `NetworkRequest` 并将其传递给 `registerNetworkCallback()` 方法以注册网络回调。在回调中,我们将检查网络是否可用,并相应地记录连接或断开连接的状态。 如果 Android 版本低于 N,则我们将注册一个广播接收器以侦听 `WifiManager.NETWORK_STATE_CHANGED_ACTION` 意图。在接收器中,我们将检查网络信息是否可用,并相应地记录连接或断开连接的状态
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值