- Android device ID
- Get my phone number in android
- 6 Answers 6
- How to get contacts’ phone number in Android
- 6 Answers 6
- Not the answer you’re looking for? Browse other questions tagged android cursor or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- Programmatically obtain the phone number of the Android phone
- 20 Answers 20
- Caveats:
- Update: This answer is no longer available as Whatsapp had stopped exposing the phone number as account name, kindly disregard this answer.
- How to find your own phone number on iOS or Android
- How to find your phone number in iOS
- How to find your phone number in Android
- Getting a call from your own number?
Android device ID
Бывает возникает необходимость получить какой-то уникальный идентификатор для Android телефона. Какие могут быть варианты? В данном топике опишу семь известных мне способов сделать это. (Точее, способов будет шесть, а вот седьмой как вариант – это комбинация всех шести предыдущих). Итак.
Android IMEI.
Думаю, Вам известно, что каждый, даже самый старый черно-белый телефон, имеет свой уникальный идентификатор – IMEI (International Mobile Equipment Identity), применяемый по большей степени в GSM сетях. Он устанавливается производителем телефона и хранится в прошивке. Можем его смело использовать в качестве требуемого идентификатора:
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String devicIMEI = telephonyManager.getDeviceId();
Для эмулятора всегда возвращается «000000000000000″, для реального телефона что-то наподобие «351256985671943″
Phone Number
Следующим образом можем получить номер телефона:
String phoneNumber = telephonyManager.getLine1Number();
Вернет строку вида: +ХХХХХХХХХХХХ (Х = [0..9])
Примечание: предыдущие два примера требуют указания в манифесте следующего пермишина:
android.permission.READ_PHONE_STATE
Псевдо-уникальный ID
Не все андроид-девайсы могут быть оснащены GSM-модулем, скажем, зато у всех у них есть производитель, который «слепил» устройство из всяких железок. Вот какраз информация об этих железках, собранная вместе, и может послужить в качестве уникального идентификатора (правда возможны и повторения). В некоторых случаях может пригодиться. Сконструируем из этих данных что-то похожее на IMEI телефона (15 знаков):
String pseudoID = «35″ +
Build.BOARD.length()%10 + Build.BRAND.length()%10 +
Build.CPU_ABI.length()%10 + Build.DEVICE.length()%10 +
Build.DISPLAY.length()%10 + Build.HOST.length()%10 +
Build.ID.length()%10 + Build.MANUFACTURER.length()%10 +
Build.MODEL.length()%10 + Build.PRODUCT.length()%10 +
Build.TAGS.length()%10 + Build.TYPE.length()%10 +
Build.USER.length()%10;
Android ID
Это еще один ID. Считается ненадежным, так как может в некоторых случаях быть и null. Обратимся к документации:
A 64-bit number (as a hex string) that is randomly generated on the device’s first boot and should remain constant for the lifetime of the device.
Ничего, пригодится:
String androidID = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
Wi-Fi Mac адрес
В качестве уникального Device Id можно использовать Mac Wi-Fi-адаптера. Для его получения необходимо в манифесте установить права: android.permission.ACCESS_WIFI_STATE
WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
String wifiMac = wifiManager.getConnectionInfo().getMacAddress();
Androif BlueTooth ID
По аналогии с Wi-Fi мак-адресом, может взять и голубозубый мак. (требуются права android.permission.BLUETOOTH и, возможно, включенный адаптер)
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
String blueToothMac = bluetoothAdapter.getAddress();
Номер 7
Вариация всех предыдущих методов. Самый простой вариант – получить все вышеописанные идентификаторы, сложить в одну строку и взять md5 хеш от этой строки.
Источник
Get my phone number in android
How can I get my phone number in Android? When I use:
it returns null, why?
6 Answers 6
Returns the phone number string for line 1, for example, the MSISDN for a GSM phone. Return null if it is unavailable.
So you have done everything right, but there is no phone number stored.
If you get null , you could display something to get the user to input the phone number on his/her own.
If the function you called returns null, it means your phone number is not registered in your contact list.
If instead of the phone number you just need an unique number, you may use the sim card’s serial number:
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:
- Get the user’s phone number as manual input from the user.
- Send a code to the user’s mobile number via SMS.
- Ask user to enter the code to confirm the phone number.
- 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.
Источник
How to get contacts’ phone number in Android
My code is as below:
I get contacts’ name success, but get phone number fail in GetPhoneNumber() .
The phones.getCount() always equal 0.
How can I modify?
6 Answers 6
Android Contact API For 2.0
For more information see this link
You need permission like —
Then, Calling the Contact Picker
Old question but I don’t see the following answer here.
Use column index ContactsContract.CommonDataKinds.Phone.NUMBER to retreive the phone number from the cursor.
Call contact picker on any button and use the below code :
|*| Add in : AndroidManifest.xml
|*| Add in : activity_name.java
Your can add this code on your Activity class:
Not the answer you’re looking for? Browse other questions tagged android cursor or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.3.40888
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
Programmatically obtain the phone number of the Android phone
How can I programmatically get the phone number of the device that is running my android app?
20 Answers 20
Caveats:
According to the highly upvoted comments, there are a few caveats to be aware of. This can return null or «» or even «. » , and it can return a stale phone number that is no longer valid. If you want something that uniquely identifies the device, you should use getDeviceId() instead.
There is no guaranteed solution to this problem because the phone number is not physically stored on all SIM-cards, or broadcasted from the network to the phone. This is especially true in some countries which requires physical address verification, with number assignment only happening afterwards. Phone number assignment happens on the network — and can be changed without changing the SIM card or device (e.g. this is how porting is supported).
I know it is pain, but most likely the best solution is just to ask the user to enter his/her phone number once and store it.
Update: This answer is no longer available as Whatsapp had stopped exposing the phone number as account name, kindly disregard this answer.
There is actually an alternative solution you might want to consider, if you can’t get it through telephony service.
As of today, you can rely on another big application Whatsapp, using AccountManager . Millions of devices have this application installed and if you can’t get the phone number via TelephonyManager , you may give this a shot.
Check actype for WhatsApp account
Of course you may not get it if user did not install WhatsApp, but its worth to try anyway. And remember you should always ask user for confirmation.
So that’s how you request a phone number through the Play Services API without the permission and hacks. Source and Full example.
In your build.gradle (version 10.2.x and higher required):
In your activity (the code is simplified):
This will generate a dialog like this:
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:
- Get the user’s phone number as manual input from the user.
- Send a code to the user’s mobile number via SMS.
- Ask user to enter the code to confirm the phone number.
- 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.
There is a new Android api that allows the user to select their phonenumber without the need for a permission. Take a look at: https://android-developers.googleblog.com/2017/10/effective-phone-number-verification.html
Just want to add a bit here to above explanations in the above answers. Which will save time for others as well.
In my case this method didn’t returned any mobile number, an empty string was returned. It was due to the case that I had ported my number on the new sim. So if I go into the Settings>About Phone>Status>My Phone Number it shows me «Unknown».
Sometimes, below code returns null or blank string.
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.
You will need to add these two permissions.
Hope this helps, Thanks!
First of all getting users mobile number is against the Ethical policy, earlier it was possible but now as per my research there no solid solution available for this, By using some code it is possible to get mobile number but no guarantee may be it will work only in few device. After lot of research i found only three solution but they are not working in all device.
There is the following reason why we are not getting.
1.Android device and new Sim Card not storing mobile number if mobile number is not available in device and in sim then how it is possible to get number, if any old sim card having mobile number then using Telephony manager we can get the number other wise it will return the “null” or “” or “. ”
Note:- I have tested this solution in following device Moto x, Samsung Tab 4, Samsung S4, Nexus 5 and Redmi 2 prime but it doesn’t work every time it return empty string so conclusion is it’s useless
- This method is working only in Redmi 2 prime, but for this need to add read contact permission in manifest.
Note:- This is also not the guaranteed and efficient solution, I have tested this solution in many device but it worked only in Redmi 2 prime which is dual sim device it gives me two mobile number first one is correct but the second one is not belong to my second sim it belong to my some old sim card which i am not using.
- In my research i have found earlier it was possible to get mobile number using WhatsApp account but now new Whatsapp version doesn’t storing user’s mobile number.
Conclusion:- Android doesn’t have any guaranteed solution to get user’s mobile number programmatically.
Suggestion:- 1. If you want to verify user’s mobile number then ask to user to provide his number, using otp you can can verify that.
- If you want to identify the user’s device, for this you can easily get device IMEI number.
Источник
How to find your own phone number on iOS or Android
Gone are the days when phone numbers were as commonly memorized as street addresses. While you once had your own phone number, your best friend’s, your crush’s, and the one for the local pizza shop all at the top of mind, the advent of smartphones has rendered this memory exercise moot. Like most people, you probably don’t call your own phone number very often — and if you do, it’s likely listed in your Favorites — so you may not know it off the top of your head.
With that reality comes the familiar grip of panic when a new acquaintance asks for your mobile phone number and you have no clue. Or maybe you’re so used to sharing your second phone number that you forgot the first!
Don’t worry, you’re not alone. Regardless of whether you’re using an iOS or Android device, you can quickly locate your own number (among other details like your IMEI number) on your phone if you know where to look. We’ll show you how to do it.
How to find your phone number in iOS
Looking up your phone number on an iOS device is easy and convenient because most iOS users are running the same version. There are two ways you can easily locate your phone number: The Contacts app or in the settings.
- Contacts: Open the Phone app, tap Contacts, and your number will be the first listed.
- Settings: Go to Settings > Phone and My Number will be the first field on the list. You can of course change, or edit, this if you wish by tapping on the number.
How to find your phone number in Android
Do not be surprised to discover some variations in the steps you need to take for finding your own mobile number on an Android device. That’s because Android users may be running different versions of the operating system and because of variations in how the operating system is implemented across device brands. So there are bound to be different interfaces depending on which device you use and which version of the OS you run. Generally, however, all roads begin from the settings.
The example below is on an LG V40 ThinQ running Android 10, but the process remains the same in Android 11 and Android 12.
- Go to settings and search for My phone number in the search bar.
- The result will give you the path: System > About phone > Status.
- Alternately, launch the Contacts app and you’ll see your own contact info right at the top.
The screenshots below show an older Samsung Galaxy S6 that runs Android 6.0 Marshmallow.
If you’re running stock Android, or something very close — for example, the Google Pixel or Nexus, or the Lenovo Moto G, X, or Z smartphones — pull up the Contacts app. You’ll see an entry titled My Info or Me ; your phone number is listed in that contact information at the top of the list.
For every Android phone, regardless of manufacturer, you’ll be able to find your phone number if you go to Settings > About Phone or About Device > Status > My phone number . Some Android phones will have SIM or SIM card status listed within Status . If this is the case with your phone, then your number will be listed there. If you don’t want to go through these many different menus, you can pull up the search bar and type in My Phone Number to directly pull up the relevant information.
It’s not hard to find your phone number once you know how to look for it, so you can help others find their numbers with just a few steps.
Getting a call from your own number?
Now that you’ve found or memorized your phone number, it might come as a shock to see if pop-up on your screen as an incoming call. The FTC has warned that some robocallers and scammers have taken number spoofing to the next level and will use your own number in hopes you answer. They have also taken to this method to get around number block, because after all, who blocks their own number? If you see an incoming call with your number on it, no it’s not you from an alternate timeline, it’s a scam so don’t pick up.
Источник