Android监听网络状态以及电池当前状态

由于要做一个产品的状态栏Toolbar要自定义电池和WIFI显示,所以需要去写代码去监测电池和WIFI的状态,下面来总结一下

我先把类贴出来

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Context.BATTERY_SERVICE
import android.content.Context.WIFI_SERVICE
import android.content.Intent
import android.content.IntentFilter
import android.databinding.DataBindingUtil
import android.net.wifi.WifiManager
import android.os.BatteryManager
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import com.hhmedic.app.patient.R
import com.hhmedic.app.patient.databinding.HpToolbarViewBinding
import com.hhmedic.app.patient.module.mangu.EventMessageBean
import kotlinx.android.synthetic.main.hp_toolbar_view.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 *  .
 */
class ToolbarView(context: Context?, attrs: AttributeSet?) : FrameLayout(context,attrs) {

    private var mBinding:HpToolbarViewBinding? = null


    init {
        initView()
    }

    private fun initView() {
        mBinding = DataBindingUtil.inflate(LayoutInflater.from(context),R.layout.hp_toolbar_view,this,true)
        EventBus.getDefault().register(this)
        updateWifiAndBattery()
    }

    fun setTitle(title:Int) {
        mBinding?.title?.setText(title)
    }

    fun setTitle(title:String) {
        mBinding?.title?.text = title
    }

    fun addBackListener(listener:OnClickListener) {
        mBinding?.back?.setOnClickListener(listener)
    }

    private fun registerReceiver() {
        val filter = IntentFilter()
        filter.addAction(WifiManager.RSSI_CHANGED_ACTION)
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
        filter.addAction(Intent.ACTION_BATTERY_CHANGED)
        context.registerReceiver(receiver, filter)
    }

    private fun unregisterReceiver() {
        context.unregisterReceiver(receiver)
    }


    private val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action ?: return
            if (action == Intent.ACTION_BATTERY_CHANGED) {
                getBattery(intent)
            } else if (action == WifiManager.WIFI_STATE_CHANGED_ACTION) {
                val wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED)
                if (wifiState == WifiManager.WIFI_STATE_DISABLED) {//如果关闭
                    EventBus.getDefault().post(EventMessageBean("wifistatu", "4"))
                    return
                }
            } else if(action == WifiManager.RSSI_CHANGED_ACTION) {
                wifi()
            }
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        registerReceiver()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        EventBus.getDefault().unregister(this)
        unregisterReceiver()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun changeWifiStatus(event: Any) {
        if (event is EventMessageBean) {
            if (event.key.equals("wifistatu")) {
                when {
                    event.value.equals("1") -> title_item_wifi.setImageResource(R.drawable.wifi1)
                    event.value.equals("2") -> title_item_wifi.setImageResource(R.drawable.wifi2)
                    event.value.equals("3") -> title_item_wifi.setImageResource(R.drawable.wifi3)
                    event.value.equals("4") -> title_item_wifi.setImageResource(R.drawable.wifi_disable)
                }
            } else if (event.key.equals("battery")) {
                when {
                    event.value.equals("0") -> title_item_battery.setImageResource(R.drawable.battery_charge)
                    event.value.equals("1") -> title_item_battery.setImageResource(R.drawable.battery_notfull)
                    event.value.equals("2") -> title_item_battery.setImageResource(R.drawable.battery_low)
                    event.value.equals("3") -> title_item_battery.setImageResource(R.drawable.battery_full)
                }
            }
        }
    }


    private fun updateWifiAndBattery() {
        wifi()
        getBattery(null)
    }

    private fun wifi() {
        val wifiManager = context.applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
        val wifiInfo = wifiManager?.connectionInfo
        //获得信号强度值
        val level = wifiInfo.rssi
        if (level <= 0 && level >= -50) {
            EventBus.getDefault().post(EventMessageBean("wifistatu", "3"))
        } else if (level < -50 && level >= -70) {
            EventBus.getDefault().post(EventMessageBean("wifistatu", "2"))
        } else if (level < -70 && level >= -80) {
            EventBus.getDefault().post(EventMessageBean("wifistatu", "1"))
        } else if (level < -80 && level >= -100) {
            EventBus.getDefault().post(EventMessageBean("wifistatu", "1"))
        } else {
            EventBus.getDefault().post(EventMessageBean("wifistatu", "4"))
        }
    }


    private fun getBattery(intent: Intent?) {
        val status = intent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
        if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
            EventBus.getDefault().post(EventMessageBean("battery", "0"))
            return
        }
        val batteryManager = context.getSystemService(BATTERY_SERVICE) as BatteryManager
        val battery = batteryManager?.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
        when (battery) {
            100 -> EventBus.getDefault().post(EventMessageBean("battery", "3"))
            in 16..99 -> EventBus.getDefault().post(EventMessageBean("battery", "1"))
            else -> EventBus.getDefault().post(EventMessageBean("battery", "2"))
        }
    }

接下来大概解释一下这个类

  1. R.layout.hp_toolbar_view这个layout就是Toolbar的显示View,我在这个View上定义了电池和WIFI显示的区域,即两个ImageView用来切换图片来表示不同状态

  2. 监听网络状态和电池状态是用BroadcastReceiver来做监听的,用不同的action来区分不同的变化的通知,以下代码很清晰可以参考一下。

private val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action ?: return
            if (action == Intent.ACTION_BATTERY_CHANGED) {
                getBattery(intent)
            } else if (action == WifiManager.WIFI_STATE_CHANGED_ACTION) {
                val wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED)
                if (wifiState == WifiManager.WIFI_STATE_DISABLED) {//如果关闭
                    EventBus.getDefault().post(EventMessageBean("wifistatu", "4"))
                    return
                }
            } else if(action == WifiManager.RSSI_CHANGED_ACTION) {
                wifi()
            }
        }
    }

注意在使用BroadcastReceiver的时候需要记住一点就是如果注册了,也要在不用的时候进行取消注册,否则会有问题。

  1. WIFI状态的检测其实分为两种一种是连接状态,另外一种是信号强度
private fun wifi() {
        val wifiManager = context.applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
        val wifiInfo = wifiManager?.connectionInfo
        //获得信号强度值
        val level = wifiInfo.rssi
        if (level <= 0 && level >= -50) {
            EventBus.getDefault().post(EventMessageBean("wifistatu", "3")) //信号极好
        } else if (level < -50 && level >= -70) {
            EventBus.getDefault().post(EventMessageBean("wifistatu", "2")) //信号一般
        } else if (level < -70 && level >= -80) {
            EventBus.getDefault().post(EventMessageBean("wifistatu", "1"))  //信号极差
        } else if (level < -80 && level >= -100) {
            EventBus.getDefault().post(EventMessageBean("wifistatu", "1"))//信号极差
        } else {
            EventBus.getDefault().post(EventMessageBean("wifistatu", "4")) //断网
        }
    }

其实3 、2、1、4这状态是自定义的,这些根据自己的爱好自定义就行,只要保证含义自己能区分就行。

  1. 电池的状态监控
private fun getBattery(intent: Intent?) {
        val status = intent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
        if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
            EventBus.getDefault().post(EventMessageBean("battery", "0"))
            return
        }
        val batteryManager = context.getSystemService(BATTERY_SERVICE) as BatteryManager
        val battery = batteryManager?.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
        when (battery) {
            100 -> EventBus.getDefault().post(EventMessageBean("battery", "3"))
            in 16..99 -> EventBus.getDefault().post(EventMessageBean("battery", "1"))
            else -> EventBus.getDefault().post(EventMessageBean("battery", "2"))
        }
    }

状态码也是根据自己喜好定义就好了。

  1. 状态变更更新图标或文字
@Subscribe(threadMode = ThreadMode.MAIN)
    fun changeWifiStatus(event: Any) {
        if (event is EventMessageBean) {
            if (event.key.equals("wifistatu")) {
                when {
                    event.value.equals("1") -> title_item_wifi.setImageResource(R.drawable.wifi1)
                    event.value.equals("2") -> title_item_wifi.setImageResource(R.drawable.wifi2)
                    event.value.equals("3") -> title_item_wifi.setImageResource(R.drawable.wifi3)
                    event.value.equals("4") -> title_item_wifi.setImageResource(R.drawable.wifi_disable)
                }
            } else if (event.key.equals("battery")) {
                when {
                    event.value.equals("0") -> title_item_battery.setImageResource(R.drawable.battery_charge)
                    event.value.equals("1") -> title_item_battery.setImageResource(R.drawable.battery_notfull)
                    event.value.equals("2") -> title_item_battery.setImageResource(R.drawable.battery_low)
                    event.value.equals("3") -> title_item_battery.setImageResource(R.drawable.battery_full)
                }
            }
        }
    }

在以上方法做了对应状态图标的动态更新,也许有人看到这代码不知道什么时候触发的,其实就是用EventBus发送了通知来触发的,具体的用法可以自己参考https://github.com/greenrobot/EventBus

0 0 vote
Article Rating
Subscribe
提醒
guest
0 评论
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x