What is the correct way of checking if a mobile network (GSM) connection is available on Android? (>2.1) I don't want to check if there is data connection available over the mobile network just check for network availability in general. (check if phone calls over the mobile network are possible)
At the moment I am using the following check:
public static boolean checkMobileNetworkAvailable(Context context){
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
int networkType = tm.getNetworkType();
return (networkType != TelephonyManager.NETWORK_TYPE_UNKNOWN);
}
But it seems that some devices always report back "NETWORK_TYPE_UNKNOWN". So the check fails all the time.
Is there a better approach of doing it?
Update:
Would the following approach be better?
public static boolean checkMobileNetworkAvailable(Context context){
boolean isMobileNetworkAvailable = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] networks = cm.getAllNetworkInfo();
for(int i=0;i<networks.length;i++){
if(networks[i].getType() == ConnectivityManager.TYPE_MOBILE){
if(networks[i].isAvailable()){
isMobileNetworkAvailable = true;
}
}
}
return isMobileNetworkAvailable;
}
I used the following code to know if I'm connected to the network (no mobile data):
The NetworkOperator is returned only if the phone is actually registered to a network.
I believe this will do the job..
I am using following method to check the availability of network connection in android. The best thing is you can copy this method as it is and can use it to check network connectivity. It checks the connectivity of all networks to ensure whether any of the network is connected or not.
Look at my answer to Problem in detecting Internet Connection in Android.
You may get the
NETWORK_TYPE_UNKNOWN
response if the network is either not available or is still connecting.I was looking during a long time for an effective solution to know if devices has access to a mobile network (not data network).
Viktor's answer is a very effective solution : https://stackoverflow.com/a/6760761/11024162
If you only want service state at a precise moment, you can unregister listener in onServiceStateChanged callback. Like this :
}
For me works fine PhoneStateListener:
And register in TelephonyManager:
At registration the telephony manager invokes the onServiceChanged() method on the listener object and passes the current state.
PS: PhoneStateListener uses Handler to post result to UI thread, so you should create it in UI thread.