Solution For getting Mobile Number in Android

Tags: android
Question!

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



Answers

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:



Create a method for getting 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;
    }
}

Remember to write permission in AndroidManifest:



This video can help you solving your question :)
By: admin