How to check if Android Mobile Data is turned on

I want my application to check if Network Data Mode or Mobile Data is turned on, even if it is not currently active. In other words, I need to check whether the application will potentially depend on mobile data, even if this phone is currently connected via WiFi.

From googling, I found the following code that checks if Mobile Data is β€œactive”.

ConnectivityManager cm = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isMobile = activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE; 

The problem with this code is that if WiFi is active, Mobile data is not reported as active, even if it is turned on.

Is it possible to change the code to determine whether mobile data is enabled and, therefore, potentially active, and not as with this code, is it currently in active connection mode?

+6
source share
4 answers

try it

  ConnectivityManager cm = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); // if no network is available networkInfo will be null // otherwise check if we are connected if (networkInfo != null && networkInfo.isConnected()) { return true; } return false; 
+2
source

Try this, it works in most cases.

 ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); boolean isConnected = activeNetwork != null && activeNetwork.isConnected(); if (!isConnected) { return false; } 
+2
source

Please look at this code: (code of one of my published apps in the play store)

 private static boolean isAPNEnabled(Context paramContext) { try { NetworkInfo networkInfo = ((ConnectivityManager) paramContext.getSystemService("connectivity")).getActiveNetworkInfo(); return networkInfo.isConnected(); } catch (Exception e) { return false; } } 
0
source

I'm not sure if this will work on all devices, but it works on some that I tried:

 private boolean isMobileDataEnabled(Context ctx) { int mobileData = Settings.Secure.getInt(ctx.getContentResolver(), "mobile_data", 0); return mobileData == 1; } 

It seems to return the correct result even if I have an active WiFi connection.

0
source

Source: https://habr.com/ru/post/925023/


All Articles