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.
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)
}
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()
}
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" />
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With