how to broadcast Receiver and MVVM?

2020-05-09 10:18发布

问题:

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