Reputation: 927
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.
Upvotes: 10
Views: 23756
Reputation: 1
Note: getActiveNetworkInfo()
was deprecated in Android 10. Use NetworkCallbacks
instead for apps that target Android 10 (API level 29) and higher.
CONNECTIVITY_ACTION
This constant was deprecated in API level 28. apps should use the more versatile requestNetwork(NetworkRequest, PendingIntent)
, registerNetworkCallback(NetworkRequest, PendingIntent)
or registerDefaultNetworkCallback(ConnectivityManager.NetworkCallback)
functions instead for faster and more detailed updates about the network changes they care about.
Upvotes: 0
Reputation: 1503
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)
}
Upvotes: 10
Reputation: 542
For the above answers which uses
networkUtils.getConnectivityStatusString(context)
is returning false just add this line in AndroidManifest.xml file
<application
android:usesCleartextTraffic="true"
......
......
Upvotes: -1
Reputation: 8666
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()
}
Upvotes: 5
Reputation: 19
Since in typical Android apps, we will need to check if the user is connected to the internet, so make a utility class with all these functions and pass in context like below:
package utilities;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class Util {
public boolean isNetworkConnected(Context c){
ConnectivityManager connectivityManager
= (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
And you can call it by:
Util utility = new Util();
Toast.makeText(getApplicationContext(),"State is :"+utility.isNetworkConnected(this), Toast.LENGTH_LONG).show();
Upvotes: 0
Reputation: 9827
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" />
Upvotes: 26
Reputation: 1974
If you want to check network status.. First create this class..
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
Then whenever you want to check status..
ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
Boolean isInternetPresent = cd.isConnectingToInternet();
Upvotes: 2
Reputation: 23638
Try out below method to get the Network status.
ConnectivityManager Class
The primary responsibilities of this class are to:
public static boolean IsNetConnected() { boolean NetConnected = false; try { ConnectivityManager connectivity = (ConnectivityManager) m_context .getSystemService(m_context.CONNECTIVITY_SERVICE); if (connectivity == null) { NetConnected = false; } else { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { NetConnected = true; } } } } } catch (Exception e) { e.printStackTrace(); NetConnected = false; } return NetConnected; }
Upvotes: 0
Reputation: 22537
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();
}
Upvotes: 10
Reputation: 93
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork.isConnectedOrConnecting();
Should check if you currently have connectivity
http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
Upvotes: 0