javaandroidandroid-networking

How to have the app check for mobile data ONLY in Android Studio


So in this app, it is required to use some sort of network because there's API calls involved. There's an error that pops up when there's no mobile data around. The thing is, it also pops up when I turn the WiFi off, while the mobile data is still on. Is there a way to only have the error message pop up for the mobile data status only and not both the WiFi and mobile data. Here's the code I believe is verifying the network state.

public static boolean verifyNetWork(@NonNull Context context) {
        ConnectivityManager cm = (ConnectivityManager)context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
            return false;
        }
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    } 

Any help and advice is appreciated. Thanks


Solution

  • Note that you need to add the ACCESS_NETWORK_STATE permission to your app's AndroidManifest.xml file in order to use the ConnectivityManager class:

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

    To check for the availability of mobile data in an Android app, you can use the ConnectivityManager class provided by the Android framework.

    public boolean isMobileDataAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    
        return activeNetworkInfo != null && activeNetworkInfo.isConnected() && activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
    }
    

    You can then call this method in your code and check its return value to determine whether mobile data is available:

    if (isMobileDataAvailable()) {
        // Mobile data is available
    } else {
        // Mobile data is not available
    }
    

    Yes, the updated code I provided checks for both mobile data and Wi-Fi.

    public boolean isMobileDataAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    
        return activeNetworkInfo != null && activeNetworkInfo.isConnected() &&
                (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE ||
                 activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI);
    }