Android phone name java

How to get an Android Device Nickname

Background

On most Android devices, users have the option to set a custom device nickname to make it easier for them to identity their device. When showing a user a list of their devices, we want their custom device name to be displayed instead of the factory default value if it’s available.

Research

I searched the web and found several different methods to read the user specified device nickname on Android:

Note: #3 requires Bluetooth permission.

Results

But how do they perform on various popular Android devices? The # columns in the table below refer to the methods used to access the device nickname referenced in the ‘Research’ section above. A green check indicates that we were able to successfully read the user’s custom device nickname.

Conclusion

There is no standardized Android API to read the user specified device nickname and not all Android devices support a custom nickname. There are ways to read this data but none work on all Android devices.

Although we didn’t find a consistent way to access the user specified device nickname, there are libraries available like AndroidDeviceNames that can provide a more readable device name than the factory set value (e.g. “sailfish”). For example, it can provide “Samsung S8+” which a user is more likely to recognize than the codename “dream2qltecan” or model number “SM-G955W”.

DISCLOSURE STATEMENT: These opinions are those of the author. Unless noted otherwise in this post, Capital One is not affiliated with, nor is it endorsed by, any of the companies mentioned. All trademarks and other intellectual property used or displayed are the ownership of their respective owners. This article is © 2019 Capital One.

Источник

Основы Contacts API в Android

Введение

Начиная с версии 5 API Android SDK интерфейс работы с контактами изменился, а основной контент провайдер Contacts и все его составляющие получили черную метку @Deprecated. Теперь за работу с контактами отвечает провайдер ContactsContract. Эти изменения связаны с изменением структуры хранения контактов, более адаптированной для Android устройств, которым требуется хранить контакты из множества разных источников и предоставлять их пользователю как единую сущность. Ведь сегодня, определенный контакт на нашем мобильном устройстве это не только имя и номер телефона, мы можем захотеть сохранить eMail, Im, Twitter, Facebook аккаунт определенного человека, и при этом, мы не хотим чтобы у нас нас появилось миллион непонятных записей. Поэтому новый Contacts API позволяет Android агрегировать похожие контакты и представлять их пользователю в одной записи, а также связывать контакт с разного рода данными.

Структура данных

На устройстве основная информация о контактах хранится в трех таблицах, на деле их там конечно больше, но мы рассмотрим основные три: contacts, raw_contacts и data. Чтобы было более наглядно я набросал простую схему в Dia.

В таблице contacts хранятся агрегированные контакты, каждая запись в этой таблице представляет собой пользовательский контакт (единую сущность) – объединение одного или нескольких сырых (необработанных) контактов из таблицы raw_contacts. Как видно на схеме, связь между этими таблицами один ко многим (1-N). Одна запись в таблице raw_contacts представляет собой так называемый сырой контакт. Сырой контакт, на языке Android, означает какой-то конкретный набор данных для определенного контакта. Но сами основные данные в этой таблице не хранятся, они хранятся в таблице data, и связь между raw_contacts и data также один ко многим. В таблице data хранятся непосредственно данные. Причем каждая строка этой таблицы это набор данных определенного типа для контакта. Какого именно типа данные хранятся в строке определяется столбцом mimetype_id, в котором содержится id типов данных определенных в таблице mimetype(например vnd.android.cursor.item/name, vnd.android.cursor.item/photo). Теперь разберемся во всем по подробней и с примерами.

Читайте также:  Bluetooth кнопки для андроид

Работаем с контактами

Хорошо, допустим мы хотим добавить контакт (Robert Smith, моб.тел. 11-22-33), как нам это сделать? В таблицу contacts мы сами, явно, не можем добавить контакт, так как система сама формирует эту таблицу агрегируя похожие raw_contacts. Идентичность контактов система определяет в основном по имени (одинаковые имена, фамилии и т.п.), но и по другим критериям, каким именно и как ими управлять можно посмотреть в документации. То есть, если мы добавим raw_contact нашего Роберта (Robert Smith) и свяжем его с данными типа vnd.cursor.android.item/phone, а потом у нас появится “похожий”, для системы, Robert Smith связанный с данными типа vnd.cursor.android.item/email и еще один с данными типа vnd.cursor.android.item/photo, то у нас в контактах будет один Robert Smith с фотографией, мобильным и email’ом.

Теперь попробуем переложить это на код. За таблицы и их поля отвечает, как я уже говорил, класс ContactsContract и его внутренние классы и интерфейсы. Например интерфейсом к таблице raw_contacts является класс ContactsContract.RawContacts, а за таблицу data класс ContactsContract.Data. Будьте внимательны когда изучаете их константы – интерфейсы к столбцам – обращайте внимание на метки read/write и read only.

Из написанного выше следует, что для начала, мы должны добавить сырой контакт, а потом связывать его с данными. Добавить пустой контакт можно так:

В контактах у вас должен появиться пустой (Unknown) контакт, ни с чем не связанный. Добавим ему имя. Чтобы это сделать, мы должны связать наш новый контакт с новыми данными используя его id, который можно достать из прошлого запроса. Основные интерфейсы к полям таблицы данных содержаться в классе-контейнере ContactsContract.CommonDataKinds и его внутренних классах и интерфейсах. Например, сейчас нам понадобиться
класс ContactsContract.CommonDataKinds.StrucruredName содержащий нужные нам константы для добавления имени, а также константу MIME типа, которой мы пометим наше поле в таблице данных.

Если мы добавим контакт таким образом, то в списке контактов у нас появиться Robert Smith. Теперь идем дальше, добавим нашему контакту еще и телефон. Для этого нам понадобиться класс ContactsContract.CommonDataKinds.Phone, который является интерфейсом к данным телефонного номера.

Теперь в контактах у нас есть Robert Smith которому можно позвонить. Но вот так добавлять контакт и данные к нему, в несколько запросов, дорого и накладно. Поэтому существует класс ContentProviderOperation, который позволяет построить запрос, который выполнит все наши операции за одну транзакцию. Именно им и рекомендуют пользоваться. Вот так можно добавить нашего Роберта используя ContentProviderOperation.

Вот таким образом в Android можно добавлять контакты. Будьте осторожны используя ContentProviderOperation, так как слишком большой запрос может долго выполняться. Вообще все операции лучше производить в отдельном потоке, потому, что у пользователя, например, может быть слабый телефон и много контактов.

В остальном все другие операции выполняются обычным образом, используя те провайдеры, которые вам необходимы, с некоторыми оговорками. Например, удаление контакта из таблицы contacts удалит все raw_contacts с ним связанные и т.д.

Вот так можно попробовать найти нашего Роберта в контактах:

На этом хотелось бы завершить статью, все же это были только основные сведения о Contacts API в Andoid. Я надеюсь мне удалось описать здесь основные принципы, а вся конкретика зависит от того, что вам необходимо сделать в процессе работы. Можно просто руководствоваться этими принципами и находить в официальной документации интерфейсы которые вам нужны для работы. Успехов!

Источник

Get Android Phone Model programmatically , How to get Device name and model programmatically in android?

I would like to know if there is a way for reading the Phone Model programmatically in Android.

I would like to get a string like HTC Dream, Milestone, Sapphire or whatever.

16 Answers 16

I use the following code to get the full device name. It gets model and manufacturer strings and concatenates them unless model string already contains manufacturer name (on some phones it does):

Читайте также:  Сравнение клавиатур для андроид

Here are a few examples of device names I got from the users:

Samsung GT-S5830L
Motorola MB860
Sony Ericsson LT18i
LGE LG-P500
HTC Desire V
HTC Wildfire S A510e

On many popular devices the market name of the device is not available. For example, on the Samsung Galaxy S6 the value of Build.MODEL could be «SM-G920F» , «SM-G920I» , or «SM-G920W8» .

I created a small library that gets the market (consumer friendly) name of a device. It gets the correct name for over 10,000 devices and is constantly updated. If you wish to use my library click the link below:

AndroidDeviceNames Library on Github

If you do not want to use the library above, then this is the best solution for getting a consumer friendly device name:

Источник

How to get the device’s IMEI/ESN programmatically in android?

To identify each devices uniquely I would like to use the IMEI (or ESN number for CDMA devices). How to access this programmatically?

22 Answers 22

This will return whatever string uniquely identifies the device (IMEI on GSM, MEID for CDMA).

You’ll need the following permission in your AndroidManifest.xml :

in order to do this.

That being said, be careful about doing this. Not only will users wonder why your application is accessing their telephony stack, it might be difficult to migrate data over if the user gets a new device.

Update: As mentioned in the comments below, this is not a secure way to authenticate users, and raises privacy concerns. It is not recommended. Instead, look at the Google+ Login API if you want to implement a frictionless login system.

The Android Backup API is also available if you just want a lightweight way to persist a bundle of strings for when a user resets their phone (or buys a new device).

In addition to the answer of Trevor Johns, you can use this as follows:

And you should add the following permission into your Manifest.xml file:

In emulator, you’ll probably get a like a «00000. » value. getDeviceId() returns NULL if device ID is not available.

I use the following code to get the IMEI or use Secure.ANDROID_ID as an alternative, when the device doesn’t have phone capabilities:

Or you can use the ANDROID_ID setting from Android.Provider.Settings.System (as described here strazerre.com).

This has the advantage that it doesn’t require special permissions but can change if another application has write access and changes it (which is apparently unusual but not impossible).

Just for reference here is the code from the blog:

Implementation note: if the ID is critical to the system architecture you need to be aware that in practice some of the very low end Android phones & tablets have been found reusing the same ANDROID_ID (9774d56d682e549c was the value showing up in our logs)

The following code helps in obtaining IMEI number of android devices :

Permissions required in Android Manifest:

NOTE: In case of tablets or devices which can’t act as Mobile Phone IMEI will be null.

to get IMEI (international mobile equipment identifier)

to get device unique id

For Android 6.0+ the game has changed so i suggest you use this;

The best way to go is during runtime else you get permission errors.

Hope this helps you or someone.

New Update:

For Android Version 6 And Above, WLAN MAC Address has been deprecated , follow Trevor Johns answer

Update:

For uniquely Identification of devices, You can Use Secure.ANDROID_ID.

Old Answer:

Disadvantages of using IMEI as Unique Device ID:

  • IMEI is dependent on the Simcard slot of the device, so it is not possible to get the IMEI for the devices that do not use Simcard. In Dual sim devices, we get 2 different IMEIs for the same device as it has 2 slots for simcard.
Читайте также:  Редактор заметок для андроид

You can Use The WLAN MAC Address string (Not Recommended For Marshmallow and Marshmallow+ as WLAN MAC Address has been deprecated on Marshmallow forward. So you’ll get a bogus value)

We can get the Unique ID for android phones using the WLAN MAC address also. The MAC address is unique for all devices and it works for all kinds of devices.

Advantages of using WLAN MAC address as Device ID:

It is unique identifier for all type of devices (smart phones and tablets).

It remains unique if the application is reinstalled

Disadvantages of using WLAN MAC address as Device ID:

Give You a Bogus Value from Marshmallow and above.

If device doesn’t have wifi hardware then you get null MAC address, but generally it is seen that most of the Android devices have wifi hardware and there are hardly few devices in the market with no wifi hardware.

Источник

Get Android Device Name

How to get Android device name? I am using HTC desire. When I connected it via HTC Sync the software is displaying the Name ‘HTC Smith’ . I would like to fetch this name via code.

How is this possible in Android?

14 Answers 14

In order to get Android device name you have to add only a single line of code:

I solved this by getting the Bluetooth name, but not from the BluetoothAdapter (that needs Bluetooth permission).

No extra permissions needed.

On many popular devices the market name of the device is not available. For example, on the Samsung Galaxy S6 the value of Build.MODEL could be «SM-G920F» , «SM-G920I» , or «SM-G920W8» .

I created a small library that gets the market (consumer friendly) name of a device. It gets the correct name for over 10,000 devices and is constantly updated. If you wish to use my library click the link below:

AndroidDeviceNames Library on Github

If you do not want to use the library above, then this is the best solution for getting a consumer friendly device name:

Example from my Verizon HTC One M8:

Try it. You can get Device Name through Bluetooth.

Hope it will help you

From android doc:

The manufacturer of the product/hardware.

The end-user-visible name for the end product.

The name of the industrial design.

Furthermore, their is lot of attribute in Build class that you can use, like:

  • os.android.Build.BOARD
  • os.android.Build.BRAND
  • os.android.Build.BOOTLOADER
  • os.android.Build.DISPLAY
  • os.android.Build.CPU_ABI
  • os.android.Build.PRODUCT
  • os.android.Build.HARDWARE
  • os.android.Build.ID

Also their is other ways you can get device name without using Build class(through the bluetooth).

Following works for me.

String deviceName = Settings.Global.getString(.getContentResolver(), Settings.Global.DEVICE_NAME);

I don’t think so its duplicate answer. The above ppl are talking about Setting Secure, for me setting secure is giving null, if i use setting global it works. Thanks anyways.

@hbhakhra’s answer will do.

If you’re interested in detailed explanation, it is useful to look into Android Compatibility Definition Document. (3.2.2 Build Parameters)

DEVICE — A value chosen by the device implementer containing the development name or code name identifying the configuration of the hardware features and industrial design of the device. The value of this field MUST be encodable as 7-bit ASCII and match the regular expression “^[a-zA-Z0-9_-]+$”.

MODEL — A value chosen by the device implementer containing the name of the device as known to the end user. This SHOULD be the same name under which the device is marketed and sold to end users. There are no requirements on the specific format of this field, except that it MUST NOT be null or the empty string («»).

MANUFACTURER — The trade name of the Original Equipment Manufacturer (OEM) of the product. There are no requirements on the specific format of this field, except that it MUST NOT be null or the empty string («»).

Источник

Оцените статью