我需要在2个不同的地方(活动和片段)提供wifi信号强度。
我能够获得信号强度,甚至可以使用片段中的数据绑定和LiveData更新UI,但是现在我希望Main活动也知道信号的状态(如果没有互联网,则出现错误弹出消息)
执行此操作的最佳方法是什么?
想到一些事情,例如。您如何看待:
1)为wifi状态创建服务,然后发出广播(每30秒左右)以更新我的Fragment和主要活动的ViewModels值
2)使用接口代替使用广播接收器
3)只需在我的活动视图模型中检查连通性,然后将其传递给其片段子级
我还应该将服务包装在协程中吗?
以下是获取wifi强度的实际代码(当前在我的ActivityViewModel中):
/**
* Changes the wifi signal value/icon
*
* This is private because we don't want to expose setting this value to the Fragment.
*/
var _signalStrengthResource = MutableLiveData<Int>()
val signalStrengthResource: LiveData<Int>
get() = _signalStrengthResource
private val _application = application
fun initWifiStatus() {
val connectivityContext = Context.WIFI_SERVICE
val wifi = Objects.requireNonNull<Context>(_application).getSystemService(connectivityContext) as WifiManager
// Wifi signal status is updated every X seconds
Timer("SettingUp", false).schedule(0, 3000) {
updateSignalStrength(wifi)
}
}
fun updateSignalStrength(wifi: WifiManager) {
val numberOfLevels = 6
val wifiInfo = wifi.connectionInfo
Log.d("MainFragmentViewModel", "Signal power : " + WifiManager.calculateSignalLevel(wifiInfo.rssi, numberOfLevels))
when (WifiManager.calculateSignalLevel(wifiInfo.rssi, numberOfLevels)) {
0 -> _signalStrengthResource.postValue(R.drawable.ic_signal_wifi_off_white_30dp)
1 -> _signalStrengthResource.postValue(R.drawable.ic_signal_wifi_0_bar_white_30dp)
2 -> _signalStrengthResource.postValue(R.drawable.ic_signal_wifi_1_bar_white_30dp)
3 -> _signalStrengthResource.postValue(R.drawable.ic_signal_wifi_2_bar_white_30dp)
4 -> _signalStrengthResource.postValue(R.drawable.ic_signal_wifi_3_bar_white_30dp)
5 -> _signalStrengthResource.postValue(R.drawable.ic_signal_wifi_4_bar_white_30dp)
}
}