- Подводные камни идентификации Android-устройства
- Тут мы видим несколько путей:
- Advertising ID
- MAC-address
- Serial Number
- Android ID
- Общий вывод
- How to Change Android Device Model Number and Name
- Requirements
- Change Android Device Model Number
- Android device ID
- How to Easily Change or Fake Your Android Device Model and Brand Name
- Things you Need
- Changing Device Model or Brand by Editing Build.prop File
- Author: Jaber Al Nahian
Подводные камни идентификации Android-устройства
Некоторым разработчикам может понадобится идентифицировать Android-устройства своих пользователей. Чаще всего это делается не для того чтобы распознать именно девайс, а для определения конкретной установки приложения. Также я встречала несколько кейсов, когда это было необходимо, если у разработчика появлялось несколько приложений и он хотел понимать, что они работают в одной среде.
Гугл говорит, что идентифицировать устройство очень просто. Но мы же говорим об Android:)
Данная статья ориентирована на приложения или библиотеки, которые не хотят привязываться к гугловым сервисам.
Итак, давайте погрузимся в это чудесное приключение по получению уникального идентификатора устройства.
Тут мы видим несколько путей:
- Advertising ID
- IMEI
- MAC-address
- Serial Number
- Android ID
Выглядит пока что не плохо, не так ли? Целых пять способов получить уникальный идентификатор для Android-устройства. Я уверена, что если вы еще пошуршите по сети, то, наверняка, найдете еще парочку других способов, но тут я вынесла самые популярные. Итак, давайте пойдем по порядку.
Advertising ID
Это уникальный для пользователя рекламный идентификатор, предоставляемый службами Google Play. Он необходим для работы рекламы, чтобы Google понимал, какую рекламу можно показывать конкретному пользователю и какая реклама уже была показана с помощью встроенных в приложения рекламных баннеров. А так же это значит, что вы лишитесь этого идентификатора, если ваше приложение будет скачано, к примеру, с Amazon, а помимо этого вам придется втащить в ваше приложение гугловые библиотеки.
Вывод: мы не идентифицируем устройство во всех случаях.
Но мы же хотим наверняка, верно? Тогда идем дальше.
Это международный идентификатор мобильного оборудования, используемый на телефонах стандарта GSM. Номер IMEI используется сетями для идентификации смартфонов и блокировки доступа в сеть украденных или занесенных в черный список девайсов. Но к сожалению с IMEI может возникнуть ряд проблем:
- Возникает ошибка «Invalid IMEI»
- IMEI можно изменить
- Для получения IMEI необходим permission:
Вывод: мы не идентифицируем устройство во всех случаях и нас еще и могут обмануть:C
MAC-address
It may be possible to retrieve a Mac address from a device’s WiFi or Bluetooth hardware. We do not recommend using this as a unique identifier. To start with, not all devices have WiFi. Also, if the WiFi is not turned on, the hardware may not report the Mac address.
Serial Number
Считается уникальным серийным номером устройства, который остается с ним до “самого конца”. Получить его можно таким способом:
А теперь про проблемы. Во-первых, для получения серийного номера потребуется запросить у пользователя разрешение READ_PHONE_STATE, а пользователь может отказать. Во-вторых, серийный номер можно изменить.
Вывод: мы не идентифицируем устройство во всех случаях, мы должны запросить permission у пользователя, которые их подбешивают и нас все еще могут обмануть.
Android ID
— Вот оно! — должны завопить мы. — Решение всех наших бед!
Android ID — это тоже уникальный идентификатор устройства. Представляет из себя 64-разрядную величину, которая генерируется и сохраняется при первой загрузке устройства.
Получить его можно вот так:
Казалось бы, такая короткая строчка избавляет нас от головной боли по идентификации устройства. Даже ребята из гугл использую Android_ID для LVL в примере.
И тут наши надежды рушатся и ничто уже не будет прежним. После обновления на Android 8 Android_ID теперь стал уникальным для каждого установленного приложения. Но, помимо этого, гугл ведь заботится о нас, так что приложения, которые были установлены до обновления останутся с прежними одинаковыми идентификаторами, которые гугл сохраняет с помощью специально написанного для этого сервиса. Но если приложение будет удалено, а затем заново установлено — Android_ID будет разным. Для того чтобы это не произошло, нужно использовать KeyValueBackup.
Но этот backup сервис нужно зарегистрировать, еще и package name указать. Более того, в документации написано, что это может не сработать по любой причине. И кто в этом виноват? Да никто, просто вот так.
Общий вывод
Если у вас хороший бекенд, то просто собирайте слепок устройства (установленные приложения, сервисы, любые данные об устройстве, которые можете достать) и сравнивайте параметры уже там, какой-то процент изменений считайте приемлемым.
Источник
How to Change Android Device Model Number and Name
Changing the model name or number is not something every Android user seeks to do but it’s still a useful trick for some users. It was really very easy for the rooted users to change Android device model number on KitKat, Lollipop and older versions of the OS but things changed after the introduction of Android 6.0 Marshmallow. So, if you own a rooted phone, here’s how you can change Android device model number using the steps described below. To change Android phone name though, you do not require root privilege.
I remember writing a tutorial on changing Android device name for WiFi, Hotspot and Bluetooth on Android devices, but what we are talking about today is pretty different.
Editing the ro.product.model entry in the Build.prop still works but doing that doesn’t change the device’s name everywhere. You can see the changed model number under Settings> About device, though.
On Android devices with Marshmallow and above, the device model name is stored in two locations, the build.prop file and in an additional location called Settings storage (com.android.providers.settings). So, unless you make the changes at both the places, you won’t be able to achieve a full device model name change on your Android device. Thanks to JBNex from XDA for coming up with a new trick that does the magic! So let’s see how to do it!!
Requirements
- A rooted Android phone or tablet.
- ADB and Fastboot drivers setup on your computer.
- OEM’s USB drivers installed on your PC.
- A root file browser app installed on the device. [googleplay url=”https://play.google.com/store/apps/details?id=com.jrummy.root.browserfree”/]
- Root file manager apps require BusyBox to work, so the app, open it and install the BusyBox script too.
Change Android Device Model Number
- Open the root file browser app on your device and grant root permission if prompted.
- Now go to system> build.prop.
- Tap build.prop and open it using the text editor.
- Now look for the following entry:
- It will look like this.
- Just tap the entry and replace the model number with the model number you want. In my case, I replaced SM-G935FD with SM-G935A.
- Having made the changes, tap the Save icon and exit the root file browser app.
- You’re already halfway, now let’s go to the other part in which we’ll be using ADB commands. You can also perform the following steps using Terminal Emulator on your device. Just make sure to run the commands without adding “adb shell” in the beginning.
- Navigate to the platform-tools directory. Its location depends on where you installed the ADB and fastboot drivers. Launch a command window by pressing the Shift+right click on the mouse on any empty space inside the folder window and selecting the “Open command window here” option.
- When the command window is launched, type the following command and hit the Enter key.
- Doing so will show your phone’s model name stored in the device’s Settings database.
- To replace the existing device name with the name of your choice.
- In my case I wanted my device name to show as “DroidViews Galaxy S9+” in place of “Galaxy S9+ DroidViews“.
- To verify if the device name has been changed successfully, issue the following command again:
- It’s time now to reboot your device.
Done! Learn more about build.prop tweaks to customize Android devices in awesome ways and use it like a pro.
Go to Settings> About device to check that the changes you made have taken effect. You have successfully changed your Android phone’s device name and model 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 хеш от этой строки.
Источник
How to Easily Change or Fake Your Android Device Model and Brand Name
Have you ever thought of changing your Android mobile or tablet device model? Actually you can change your Android device model very easily and this is helpful in some cases – for example you can make your device appear to be another particular device to any app. Or ever you faced any device restriction on Google Play while installing an app or game? For example a game developer can restrict your device from installing a particular game and make it available on other high-end devices like Galaxy Note 3 (just example) on Google Play just because that game isn’t optimized for your device or may run poorly. But there’s a big chance that your device could play that game. Now if you change your device model to Galaxy Note 3, you will be able to install that game from store – though it may not run well. Or you may want to show a different device model to an app for achieving something.
Things you Need
1. Phone must be rooted.
2. A File Manager with root support and built-in text editor.
Changing Device Model or Brand by Editing Build.prop File
For this procedure, I’ll use a free and powerful file-manager app X-plore. It’s a dual panel file explorer with root support and in-built text editor including many other features.
1. After downloading and installing X-plore, open it up, go to “Configuration” > “Root Access” and make it “Superuser + Mount writable” (assuming your phone is pre-rooted).
2. Now from /(Root) drive, locate /system folder. You should able to see a file named build.prop in that directory. This file contains some text strings used by OS and other apps to identify some of device’s information. Now long press on it, choose ‘Edit text’. Now you are ready to edit the file. Here, in lines, look for ro.product.model=**** and ro.product.manufacturer=****. Now change the value to any name after “=” as you want your device pretend to be. For example if you want your device pretend to be Galaxy S5(model SM-G900), the lines should be followings:
ro.product.model=SM-G900
ro.product.manufacturer=Samsung
You can set any name or number here though.
3. Now before closing the editor, got to options then save it. Or you should be asked if you close the editor without saving it. After successfully saving it, restart your device now. Now you have finished changing your device model.
It should reflect “About Device” info in Android settings too like following:
Note: Your network operator will see your fake model and vendor.
BTW, though it’s very easy to change or fake your Android mobile or tablet model, I wouldn’t recommend doing it unless you really need it. Because it may introduce malfunction to your device including existing apps incompatibility.
Author: Jaber Al Nahian
Jaber is a Programmer and Tech Enthusiast Geek from Dhaka, Bangladesh. He is the founder and Chief-Editor of TechGainer. While he is away from his keyboard, either he’s fishing or messing with wildlife. In case, you can contact him at rijans[at]techgainer[dot]com.
Источник