Programmatically obtain the phone number of the Android phone

后端 未结 18 1738
南笙
南笙 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:54

    Sometimes, below code returns null or blank string.

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

    With below permission

    
    

    There is another way you will be able to get your phone number, I haven't tested this on multiple devices but above code is not working every time.

    Try below code:

    String main_data[] = {"data1", "is_primary", "data3", "data2", "data1", "is_primary", "photo_uri", "mimetype"};
    Object object = getContentResolver().query(Uri.withAppendedPath(android.provider.ContactsContract.Profile.CONTENT_URI, "data"),
            main_data, "mimetype=?",
            new String[]{"vnd.android.cursor.item/phone_v2"},
            "is_primary DESC");
    if (object != null) {
        do {
            if (!((Cursor) (object)).moveToNext())
                break;
            // This is the phoneNumber
            String s1 = ((Cursor) (object)).getString(4);
        } while (true);
        ((Cursor) (object)).close();
    }
    

    You will need to add these two permissions.

    
    
    

    Hope this helps, Thanks!

提交回复
热议问题