开发者

What is the correct way of checking for mobile network available (no data connection)

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.TY开发者_如何学JAVAPE_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):

    public static Boolean isMobileAvailable(Context appcontext) {       
    TelephonyManager tel = (TelephonyManager) appcontext.getSystemService(Context.TELEPHONY_SERVICE);       
    return ((tel.getNetworkOperator() != null && tel.getNetworkOperator().equals("")) ? false : true);      
}

The NetworkOperator is returned only if the phone is actually registered to a network.


For me works fine PhoneStateListener:

private static class YourListener extends PhoneStateListener {
    @Override
    public void onServiceStateChanged(ServiceState serviceState){           
        if (serviceState.getState() == ServiceState.STATE_IN_SERVICE) {
             // connected to cellular network
        }
    }       
}

And register in TelephonyManager:

TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
YourListener listener = new YourListener();
tm.listen(listener, PhoneStateListener.LISTEN_SERVICE_STATE);

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.


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.

/**
 * Check the hardware if there are connected to Internet or not.
 * This method gets the list of all available networks and if any one of 
 * them is connected returns true. If none is connected returns false.
 * 
 * @param context {@link Context} of the app.
 * @return <code>true</code> if connected or <code>false</code> if not
 */
public static boolean isNetworkAvailable(Context context) {
    boolean available = false;
    try {
        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) {
                        available = true;
                    }
                }
            }
        }
        if (available == false) {
            NetworkInfo wiMax = connectivity.getNetworkInfo(6);

            if (wiMax != null && wiMax.isConnected()) {
                available = true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return available;
}


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 believe this will do the job..

ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (manager != null) {
            NetworkInfo info = manager.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                networkAvailable = true;
            }


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 :

private inner class PhoneListener : PhoneStateListener(){
override fun onServiceStateChanged(serviceState: ServiceState?) {
    if (serviceState?.state != ServiceState.STATE_IN_SERVICE) {

        //Behavior when no mobile network

    }
    //unregister listener after one callback call
    //phoneListener is the PhoneListener you previously create to register listener
    val tel = requireContext().getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
    tel.listen(phoneListener, PhoneStateListener.LISTEN_NONE)
}

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜