-6

Using Telephony Manager returns null value for Mobile number, I want to get Mobile Number directly in to the app without asking user.

2 Answers2

0

You can use the TelephonyManager to do this:

TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); 
String number = tm.getLine1Number();

The getLine1Number() will return null if the number is "unavailable", but it does not say when the number might be unavailable.

You'll need to give your application permission to make this query by adding the following to your Manifest:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Jitesh Prajapati
  • 2,533
  • 4
  • 29
  • 51
0

Try the given below method for generating country code

  private void getCountryCode() {
        int code = 0;
        TelephonyManager telephonyManager = (TelephonyManager) getActivity().
                getSystemService(Context.TELEPHONY_SERVICE);
        String CountryISO = telephonyManager.getSimCountryIso().toString().toUpperCase();
        ;
        //String NetworkCountryIso = telephonyManager.getNetworkCountryIso().toString();
        String number = telephonyManager.getLine1Number();
        code = getCountryCodeForRegion(CountryISO);
        Log.i("CountryISO", "CountryISO " + CountryISO);
        Log.i("code", "code " + code);
        Log.i("number ", "number " + number);


    }

Gets CountryCode from regionCode

public int getCountryCodeForRegion(String regionCode) {
    int result = -1;
    try {
        Class c = Class.forName("com.android.i18n.phonenumbers.PhoneNumberUtil");
        Method getInstance = c.getDeclaredMethod("getInstance");
        Method getCountryCodeForRegion = c.getDeclaredMethod("getCountryCodeForRegion", String.class);

        Object instance = getInstance.invoke(null);
        Integer code = (Integer) getCountryCodeForRegion.invoke(instance, regionCode);
        result = code;
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } finally {
        return result;
    }
}

Don't forget to add permission in AndroidManifest:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Rissmon Suresh
  • 13,173
  • 5
  • 29
  • 38