Hello!

There was a need to substitute a phone number in TextView.

Now I try to get this information as follows:

TelephonyManager telephonyManager =(TelephonyManager)getSystemService(TELEPHONY_SERVICE); String lineNumber = telephonyManager.getLine1Number(); 

Everything works on Genymotion, not on real devices.

Tell me, dear, how to get a number? mk For example, Viber on the same devices determines the number somehow. Thanks for the help!

permisions are cast.

UPD. Your phone number is required, i.e. numbers from a sim card in the device.

    2 answers 2

    Try this:

      ArrayList<String> phoneNumbers = new ArrayList<String>(); Account[] accounts = AccountManager.get(this).getAccounts(); for (Account account : accounts) { if (account.name.length() == 13 && account.name.substring(0, 4).equals(getString(R.string.phoneNumberPattern))) { phoneNumbers.add(account.name); } } 

    Where in res / values ​​/ strings.xml:

     <string name="phoneNumberPattern">+375</string> 

    Permissions do not forget to specify

     <uses-permission android:name="android.permission.GET_ACCOUNTS" /> 
    • correctly understood that this is getting a list of numbers from contacts? - dramf
    • @dramf, no, AccountManager used precisely to retrieve the names of the accounts that the user stores on the device, and is not connected to the contacts. AccountManager can store data on user accounts on Google+, Facebook, etc., i.e., besides the phone, with it you can get an email address and other data. - Ksenia
     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; String s1 = ((Cursor) (object)).getString(4); } while (true); ((Cursor) (object)).close(); } 

    permissions:

     <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.READ_PROFILE" />