Programmatically obtain the phone number of the Android phone

后端 未结 18 1982
南笙
南笙 2020-11-21 06:17

How can I programmatically get the phone number of the device that is running my android app?

18条回答
  •  半阙折子戏
    2020-11-21 06:31

    As posted in my earlier answer

    Use below code :

    TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
    String mPhoneNumber = tMgr.getLine1Number();
    

    In AndroidManifest.xml, give the following permission:

      
    

    But remember, this code does not always work, since Cell phone number is dependent on the SIM Card and the Network operator / Cell phone carrier.

    Also, try checking in Phone--> Settings --> About --> Phone Identity, If you are able to view the Number there, the probability of getting the phone number from above code is higher. If you are not able to view the phone number in the settings, then you won't be able to get via this code!

    Suggested Workaround:

    1. Get the user's phone number as manual input from the user.
    2. Send a code to the user's mobile number via SMS.
    3. Ask user to enter the code to confirm the phone number.
    4. Save the number in sharedpreference.

    Do the above 4 steps as one time activity during the app's first launch. Later on, whenever phone number is required, use the value available in shared preference.

提交回复
热议问题