Skip to content Skip to sidebar Skip to footer

How To Check Internet Connectivity Continuously In Background While Android Application Running

I want to check internet connectivity continuously in background while my android application running. I mean from starting of the application to the end of the application. How ca

Solution 1:

I know I am late to answer this Question. But here is a way to monitor the Network Connection Continuously in an Activity/Fragment.

We will use Network Callback to monitor our connection in an Activity/Fragment

first, declare two variable in class

// to check if we are connected to NetworkbooleanisConnected=true;

// to check if we are monitoring NetworkprivatebooleanmonitoringConnectivity=false;

Next, We will write the Network Callback Method

privateConnectivityManager.NetworkCallback connectivityCallback
            = newConnectivityManager.NetworkCallback() {
        @OverridepublicvoidonAvailable(Network network) {
            isConnected = true;
            LogUtility.LOGD(TAG, "INTERNET CONNECTED");
        }

        @OverridepublicvoidonLost(Network network) {
            isConnected = false;
            LogUtility.LOGD(TAG, "INTERNET LOST");
        }
    };

Now Since we have written our Callback we will Now write a method which will monitor our Network Connection, and in this method, we will register our NetworkCallback.

// Method to check network connectivity in Main ActivityprivatevoidcheckConnectivity() {
        // here we are getting the connectivity service from connectivity managerfinalConnectivityManagerconnectivityManager= (ConnectivityManager) getSystemService(
                Context.CONNECTIVITY_SERVICE);

        // Getting network Info// give Network Access Permission in ManifestfinalNetworkInfoactiveNetworkInfo= connectivityManager.getActiveNetworkInfo();

        // isConnected is a boolean variable// here we check if network is connected or is getting connected
        isConnected = activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();

        if (!isConnected) {
            // SHOW ANY ACTION YOU WANT TO SHOW// WHEN WE ARE NOT CONNECTED TO INTERNET/NETWORK
            LogUtility.LOGD(TAG, " NO NETWORK!");
// if Network is not connected we will register a network callback to  monitor network
            connectivityManager.registerNetworkCallback(
                    newNetworkRequest.Builder()
                            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                            .build(), connectivityCallback);
            monitoringConnectivity = true;
        }

    }

All our work is almost finished we just need to call our checkConnectivity(), the method in onResume() of our Activity/Fragment

@Override
    protected void onResume() {
        super.onResume();
        checkConnectivity();
    }

*unRegister the NetworkCallback in onPause() ,method of your Activity/Fragment *

@OverrideprotectedvoidonPause() {
        // if network is being moniterd then we will unregister the network callbackif (monitoringConnectivity) {
            finalConnectivityManagerconnectivityManager= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            connectivityManager.unregisterNetworkCallback(connectivityCallback);
            monitoringConnectivity = false;
        }
        super.onPause();
    }

That's it, just add this code in which every class of your Activity/Fragment were you need to monitor the Network!.And don't forget to unregister it!!!

Solution 2:

Create class that extends BroadcastReceiver, use ConnectivityManager.EXTRA_NO_CONNECTIVITY to get connection info.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.widget.Toast;

publicclassCheckConnectivityextendsBroadcastReceiver{

@OverridepublicvoidonReceive(Context context, Intent arg1) {

    booleanisConnected= arg1.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
    if(isConnected){
        Toast.makeText(context, "Internet Connection Lost", Toast.LENGTH_LONG).show();
    }
    else{
        Toast.makeText(context, "Internet Connected", Toast.LENGTH_LONG).show();
    }
   }
 }

Add this permission in mainfest too

<uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permissionandroid:name="android.permission.INTERNET" />

Solution 3:

In Activity or fragment

publicstaticfinalStringBROADCAST="checkinternet";
IntentFilter intentFilter;

inside oncreate

   intentFilter = newIntentFilter();
   intentFilter.addAction(BROADCAST);
   Intent serviceIntent = newIntent(this,Networkservice.class);
   startService(serviceIntent);
   if (Networkservice.isOnline(getApplicationContext())){
       Toast.makeText(getApplicationContext(),"true",Toast.LENGTH_SHORT).show();
   }else
       Toast.makeText(getApplicationContext(),"false",Toast.LENGTH_SHORT).show();

outside oncreate

publicBroadcastReceiver broadcastReceiver=newBroadcastReceiver() {
    @OverridepublicvoidonReceive(Context context, Intent intent) {
        if (intent.getAction().equals(BROADCAST)){
            if (intent.getStringExtra("online_status").equals("true")){
                Toast.makeText(getApplicationContext(),"true",Toast.LENGTH_SHORT).show();
                Log.d("data","true");
            }else {
                Toast.makeText(getApplicationContext(), "false", Toast.LENGTH_SHORT).show();
                Log.d("data", "false");
            }
        }
    }
};

@OverrideprotectedvoidonRestart() {
    super.onRestart();
    registerReceiver(broadcastReceiver,intentFilter);
}

@OverrideprotectedvoidonPause() {
    super.onPause();
    unregisterReceiver(broadcastReceiver);
}

@OverrideprotectedvoidonResume() {
    super.onResume();
    registerReceiver(broadcastReceiver,intentFilter);
}

//class

publicclassNetworkserviceextendsService {

@OverridepublicvoidonCreate() {
    super.onCreate();
}

@Nullable@Overridepublic IBinder onBind(Intent intent) {
    thrownewUnsupportedOperationException("Not yet implemented");
}

@OverridepublicintonStartCommand(Intent intent, int flags, int startId) {
    handler.post(perioud);
    return START_STICKY;
}
publicstaticbooleanisOnline(Context context){
    ConnectivityManagercm= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo nf=cm.getActiveNetworkInfo();
    if (nf!=null&&nf.isConnectedOrConnecting())
        returntrue;
        elsereturnfalse;
}
Handler handler=newHandler();
privateRunnableperioud=newRunnable() {
    @Overridepublicvoidrun() {
        handler.postDelayed(perioud,1*1000- SystemClock.elapsedRealtime()%1000);

        Intentintent=newIntent();
        intent.setAction(MainActivity.BROADCAST);
        intent.putExtra("online_status",""+isOnline(Networkservice.this));
        sendBroadcast(intent);
    }
};
}

Solution 4:

The Android system already does that for you. Instead of constantly polling the phone for the network state, register BroadcastReceivers for WiFi and network state changes and process the Intents sent by the system when the WiFi or network state changes.

Have a look at this question for more information on this.

Once you register your BroadcastReceiver, the network state change listening will happen in the background (in the OS) and an Intent will be sent to your receivers on the UI thread (most likely) when the network state changes. If you want to receive the Intents on a background thread, check this question for more info.

Solution 5:

You can also try this service Class. Just set the time interval in seconds and the url to ping:

Android Check Internet Connection

Just remember to add the service to the Manifest file, and add the permissions

Post a Comment for "How To Check Internet Connectivity Continuously In Background While Android Application Running"