Android service to check internet connectivity?

前端 未结 2 1023
终归单人心
终归单人心 2020-12-01 02:14

I want to create an Android service, which notifies the main activity whenever disconnects and when internet reconnects again. I have following function for checking interne

相关标签:
2条回答
  • 2020-12-01 02:51

    This is a Kotlin version, following Francesco Laurita's solution:

    private val broadcastReceiver by lazy {
        NetworkListener.create({
            btnOnlineVideos.visibility = View.VISIBLE
        }, {
            btnOnlineVideos.visibility = View.GONE
        })
    }
    
    override fun onResume() {
        super.onResume()
    
        NetworkListener.register(this, broadcastReceiver)
    }
    
    override fun onPause() {
        super.onPause()
    
        NetworkListener.unregister(this, broadcastReceiver)
    }
    

    For this to work I simply override the onResume and onPause methods, to register and unregister the BroadcastReceiver.

    How does this work?

    I created the following class that helps to initialize, register and unregister the BroadcastReceiver. That way there is no need to repeate most of the boilerplate code.

    package com.programacionymas.app.services
    
    import android.content.BroadcastReceiver
    import android.content.Context
    import android.content.Intent
    import android.content.IntentFilter
    import android.net.ConnectivityManager
    import android.net.NetworkInfo
    import android.os.Parcelable
    import android.util.Log
    
    object NetworkListener {
    
        fun create(onNetworkUp: () -> Unit, onNetworkDown: () -> Unit): BroadcastReceiver {
            return object : BroadcastReceiver() {
                override fun onReceive(context: Context, intent: Intent) {
    
                    intent.extras?.getParcelable<Parcelable>("networkInfo")?.let {
                        val info = it as NetworkInfo
                        val state: NetworkInfo.State = info.state
    
                        Log.d("BroadcastReceiver", "$info $state")
                        if (state === NetworkInfo.State.CONNECTED) {
                            onNetworkUp()
                        } else {
                            onNetworkDown()
                        }
                    }
    
                }
            }
        }
    
        fun register(context: Context, broadcastReceiver: BroadcastReceiver) {
            val intentFilter = IntentFilter()
            intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
            context.registerReceiver(broadcastReceiver, intentFilter)
        }
    
        fun unregister(context: Context, broadcastReceiver: BroadcastReceiver) {
            context.unregisterReceiver(broadcastReceiver)
        }
    
    }
    

    In case you need to execute sentences only for one of the states, you can pass a null anonymous function too:

    private val broadcastReceiver by lazy {
        NetworkListener.create(null, {
            toast(getString(R.string.check_your_internet))
            finish()
        })
    }
    

    And declare the parameters as optionals in the create method:

    fun create(onNetworkUp: (()->Unit)?, onNetworkDown: (()->Unit)?): BroadcastReceiver {/* ... */}
    

    As well as invoking the functions only if they were sent as arguments:

    if (state === NetworkInfo.State.CONNECTED) {
        onNetworkUp?.invoke()
    } else {
        onNetworkDown?.invoke()
    }
    
    0 讨论(0)
  • 2020-12-01 03:01

    Services are designed for long backgroud running task. You should use a BroadcastReceiver:

    This is a sample method I use to monitor the network state into my main Activity:

    private void installListener() {
    
            if (broadcastReceiver == null) {
    
                broadcastReceiver = new BroadcastReceiver() {
    
                    @Override
                    public void onReceive(Context context, Intent intent) {
    
                        Bundle extras = intent.getExtras();
    
                        NetworkInfo info = (NetworkInfo) extras
                                .getParcelable("networkInfo");
    
                        State state = info.getState();
                        Log.d("InternalBroadcastReceiver", info.toString() + " "
                                + state.toString());
    
                        if (state == State.CONNECTED) {
    
                            onNetworkUp();
    
                        } else {
    
                            onNetworkDown();
    
                        }
    
                    }
                };
    
                final IntentFilter intentFilter = new IntentFilter();
                intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
                registerReceiver(broadcastReceiver, intentFilter);
            }
        }
    

    Remember to call unregisterReceiver when the onDestroy event occurs

    Hope this help.

    0 讨论(0)
提交回复
热议问题