Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to monitor network status in android

hey i am new in android please anyone help me. I just wanted to know the names of libraries that enables me to monitor network connectivity.

like image 319
Amol Desai Avatar asked Sep 05 '13 09:09

Amol Desai


4 Answers

A small class for kotlin, which supports monitoring the status of the Internet before and after the 24 (Andoird P) version of sdk. Just create/inject this class and add an observer. In the comments version without LiveData.

class ConnectivityListener(private val context: Context) {

    val isConnected = MutableLiveData<Boolean>()

    //region used on api < 24
    private val intentFilter by lazy {
        IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
    }

    private val networkBroadcastReceiver by lazy {
        object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                val isConn = isConnected()
                isConnected.postValue(isConn)
            }
        }
    }
    //endregion

    private val networkCallback by lazy {
        object : ConnectivityManager.NetworkCallback() {
            override fun onAvailable(network: Network) {
                isConnected.postValue(true)
            }

            override fun onLost(network: Network) {
                isConnected.postValue(false)
            }
        }
    }

    init {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            getConnectivityManager()?.registerDefaultNetworkCallback(networkCallback)
        } else {
            context.registerReceiver(networkBroadcastReceiver, intentFilter)
        }
    }

    fun isConnected(): Boolean {
        val activeNetwork = getConnectivityManager()?.activeNetworkInfo
        val isConnected = activeNetwork?.isConnectedOrConnecting == true
        return isConnected
    }

    fun getConnectivityManager() = getSystemService(context, ConnectivityManager::class.java)
}
like image 180
Zakhar Rodionov Avatar answered Oct 16 '22 15:10

Zakhar Rodionov


ConnectivityManager.CONNECTION_ACTION is deprecated on Android P, so you'll have to use a combination of solutions based on API level.

First declare the following permissions in your AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
enum class InternetConnectionStatus {
  CONNECTED,
  DISCONNECTED
}

I put the following code in my Application class to avoid being affected by configuration changes.

private var connectionStatusSubject: BehaviorSubject<InternetConnectionStatus> =
    BehaviorSubject.create()


fun observeNetworkChanges() {
    // getSystemService() is the core-ktx version
    val connectivityManager: ConnectivityManager? = getSystemService()
    if (
        BUILD.VERSION.SDK_INT >= BUILD.VERSION_CODES.P &&
        connectivityManager != null
    ) {
      val callback = NetworkChangeCallback(connectionStatusSubject, connectivityManager)
      connectivityManager.registerDefaultNetworkCallback(callback)
    } else {
      val networkChangeBroadcastReceiver =
        NetworkChangeBroadcastReceiver(connectionStatusSubject)
      val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
      registerReceiver(networkChangeBroadcastReceiver, filter)
    }
  }
// API P+
class NetworkChangeCallback(
  private val subject: BehaviorSubject<InternetConnectionStatus>,
  connectivityManager: ConnectivityManager
) : NetworkCallback() {

  init {
    val network: Network? = connectivityManager.activeNetwork
    if (network == null) {
      subject.onNext(DISCONNECTED)
    } else {
      val capabilities: NetworkCapabilities? = connectivityManager.getNetworkCapabilities(network)
      if (capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true) {
        subject.onNext(CONNECTED)
      } else {
        subject.onNext(DISCONNECTED)
      }
    }
  }

  override fun onAvailable(network: Network) {
    subject.onNext(CONNECTED)
  }

  override fun onLost(network: Network) {
    subject.onNext(DISCONNECTED)
  }
}
// Below API P
class NetworkChangeBroadcastReceiver(
  private val subject: BehaviorSubject<InternetConnectionStatus>
) : BroadcastReceiver() {
  override fun onReceive(
    context: Context,
    intent: Intent
  ) {
    val noConnectivity: Boolean = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)
    if (noConnectivity) {
      subject.onNext(DISCONNECTED)
    } else {
      subject.onNext(CONNECTED)
    }
  }
}

I'm using RxJava and a BehaviorSubject to turn network status into an Observable, but you can just as easily replace this with a callback with something like

interface NetworkChangedListener {
  fun onConnected()
  fun onDisconnected()
}
like image 36
Andrew Orobator Avatar answered Oct 16 '22 17:10

Andrew Orobator


Just create a broadcast receiver with CONNECTIVITY_CHANGE action. And you will get a broadcast whenever network connectivity will change.

NetworkUtil.java

public class NetworkUtil {

    public static int TYPE_WIFI = 1;
    public static int TYPE_MOBILE = 2;
    public static int TYPE_NOT_CONNECTED = 0;


    public static int getConnectivityStatus(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                return TYPE_WIFI;

            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                return TYPE_MOBILE;
        } 
        return TYPE_NOT_CONNECTED;
    }

    public static String getConnectivityStatusString(Context context) {
        int conn = NetworkUtil.getConnectivityStatus(context);
        String status = null;
        if (conn == NetworkUtil.TYPE_WIFI) {
            status = "Wifi enabled";
        } else if (conn == NetworkUtil.TYPE_MOBILE) {
            status = "Mobile data enabled";
        } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
            status = "Not connected to Internet";
        }
        return status;
    }
}

Broadcast Receiver to handle changes in Network state

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {

        String status = NetworkUtil.getConnectivityStatusString(context);

        Toast.makeText(context, status, Toast.LENGTH_LONG).show();
    }
}

AndroidMenifest.xml

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

UPDATE

Permissions required to access network state:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
like image 29
Vipul Purohit Avatar answered Oct 16 '22 17:10

Vipul Purohit


Your question is not clear!
If checking the network connection is what you want, the following will do.

// Check network connection
private boolean isNetworkConnected(){
    ConnectivityManager connectivityManager 
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();    
}
like image 38
Lazy Ninja Avatar answered Oct 16 '22 15:10

Lazy Ninja