Home » Android » Android service to check internet connectivity?

Android service to check internet connectivity?

Posted by: admin May 14, 2020 Leave a comment


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 internet connectivity:.

private boolean haveInternet(){
        NetworkInfo info=(NetworkInfo)((ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

        if(info==null || !info.isConnected()){
            return false;
            //here is the roaming option you can change it if you want to disable internet while roaming, just return false
            return true;
        return true;

But I want to know, how to use it in a service.

How to&Answers:

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() {

                public void onReceive(Context context, Intent intent) {

                    Bundle extras = intent.getExtras();

                    NetworkInfo info = (NetworkInfo) extras

                    State state = info.getState();
                    Log.d("InternalBroadcastReceiver", info.toString() + " "
                            + state.toString());

                    if (state == State.CONNECTED) {


                    } else {




            final IntentFilter intentFilter = new IntentFilter();
            registerReceiver(broadcastReceiver, intentFilter);

Remember to call unregisterReceiver when the onDestroy event occurs

Hope this help.