Fix null context error in network utils (#2184)

This commit is contained in:
Vivek Maskara 2018-12-20 18:25:21 +05:30 committed by Adam Jones
parent b9274c0335
commit 4b58f16557
2 changed files with 88 additions and 4 deletions

View file

@ -1,21 +1,34 @@
package fr.free.nrw.commons.utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import javax.annotation.Nullable;
public class NetworkUtils {
public static boolean isInternetConnectionEstablished(Context context) {
/**
* https://developer.android.com/training/monitoring-device-state/connectivity-monitoring#java
* Check if internet connection is established.
* @param context context passed to this method could be null.
* @return Returns current internet connection status. Returns false if null context was passed.
*/
@SuppressLint("MissingPermission")
public static boolean isInternetConnectionEstablished(@Nullable Context context) {
if (context == null) {
return false;
}
ConnectivityManager cm =
(ConnectivityManager)context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
(ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) {
return false;
}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
}