how to broadcast Receiver and MVVM?

本小妞迷上赌 提交于 2020-04-07 08:00:07

问题


my manifest

<receiver android:name=".ui.receiver.NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>

and NetworkChangeReceiver Class

class NetworkChangeReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        val connMgr = context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val activeNetwork: NetworkInfo? = connMgr.activeNetworkInfo
        val isConnected: Boolean? = activeNetwork?.isConnected


        if(isConnected == null) {
            Timber.d("Test Checked is Connected null ")

        } else {
            Timber.d("Test Checked Network is Connected !! ")
        }
    }
}

I going to detect the network here.

If my mainViewModel detects what I've detected here, I'm trying to bring up an image, but I don't know what to do

Image is being visualized using live data and if the network changes here, I want to change the visibility of the image in my MainView Model.


回答1:


Use your Application class. either have a LiveData in it or a reference to a shared ViewModel. You can access Application using context.getApplicationContext() from NetworkChangeReceiver



来源:https://stackoverflow.com/questions/60629906/how-to-broadcast-receiver-and-mvvm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!