views:

1765

answers:

4

The only way I've found of retrieving MCC and MNC is by overriding an activity's onConfigurationChanged method, as such:

public void onConfigurationChanged(Configuration config)
{
 super.onConfigurationChanged(config);
 DeviceData.MCC = "" + config.mcc;
 DeviceData.MNC = ""  +config.mnc;
}

However, I need this data as soon as the app starts and can't wait for the user to switch the phone's orientation or equivalent to trigger this method. Is there a better way to access the current Configuration object?

+4  A: 

The TelephonyManager has a method to return the MCC+MNC as a String (getNetworkOperator()) which will do you what you want. You can get access it via:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    String networkOperator = tel.getNetworkOperator();

    if (networkOperator != null) {
        int mcc = Integer.parseInt(networkOperator.substring(0, 3));
        int mnc = Integer.parseInt(networkOperator.substring(3));
    }
}
jargonjustin
+1  A: 

you can access the current configuration by getResources().getConfiguration() does the trick.

Rudolf
A: 

Okay, it turns out that the getResources().getConfiguration().mcc trick is likely better for most purposes, because with the other one if the person puts their phone in airplane mode or otherwise uses Wi-Fi, then it returns an empty MCC.

Artem
A: 

You do know there are two MCC/MNC's for an active phone? (One is the country code and carrier id for the Sim card, the other is for the network/cell tower in use.)

If the getResources().getConfiguration().mcc is not empty in airplane mode, it's the Sim value TelephonyManager.getSimOperator(), not the tower value TelephonyManager.getNetworkOperator().

I don't know which the OP wants, but Answer 3 will give him different results than his original code if the getConfiguration is really the Sim values.

danS