How to Access Wifi MacAddress on latest Android devices Programmatically? - android

I was looking for the attributes which make a wifi Access point unique from others so macAddress is one.
Now i'm trying to find the macAddress of connected wifi. I'm following this article which works on android 6.0 (author said) but getting an error on android 11 that Attempt to get length of null array on i in 0..it.hardwareAddress.size. which means hardwareAddress array is null.
So how can we access MacAddress of Wifi on the latest android devices?
below is the code i tried:
fun getMacAddress(): String {
var stringMac = "default"
try {
val networkInterfaceList = Collections.list(NetworkInterface.getNetworkInterfaces())
for (it in networkInterfaceList) {
if (it.name.lowercase() == "wlan0") {
Log.d(TAG, "getMacAddress: Yes Equals")
for (i in 0..it.hardwareAddress.size) {
var stringMacByte =
Integer.toHexString((it.hardwareAddress[i] and 0xFF.toByte()).toInt())
if (stringMacByte.length == 1) {
stringMacByte = "0$stringMacByte"
}
stringMac = stringMac + stringMacByte.toUpperCase() + ":"
}
break
}
}
return stringMac
} catch (e: SocketException) {
return stringMac
}
}

change integer.toHexstring for String.format("%02X", x), because when your mac_addr contains 0 (zero), to convert to integer will be dissapear, and you will be got an 11 digits mac, that its wrong, it should be contain 12 chars;

Related

How to get my device bluetooth id.i try to get but they all time return 02:00:00:00:00:00

Hello I try to get my Bluetooth device id but that's not working.
i try below code so can you check which mistake is i made in that.
public static String getBluetoothMacAddress(Context context) {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
String bluetoothMacAddress = "0";
try {
Field mServiceField = bluetoothAdapter.getClass().getDeclaredField("mService");
mServiceField.setAccessible(true);
Object btManagerService = mServiceField.get(bluetoothAdapter);
if (btManagerService != null) {
bluetoothMacAddress = (String) btManagerService.getClass()
.getMethod("getAddress").invoke(btManagerService);
Utils.printLog("bluetoothMacAddress ", bluetoothMacAddress);
}
bluetoothMacAddress= android.provider.Settings.Secure.getString(context.getContentResolver(), "bluetooth_address");
} catch (Exception e) {
Utils.printLog("bluetoothMacAddress1 ", e.getMessage());
}
if (bluetoothMacAddress == null || bluetoothMacAddress.equals("") || bluetoothMacAddress.equals("02:00:00:00:00:00")) {
bluetoothMacAddress = "0";
}
Utils.printLog("bluetoothMacAddress ", bluetoothMacAddress);
return bluetoothMacAddress;
}
You mac address is a sort of id actually but on network layer, so that network can identify your device. You should always get same mac address for particular device, though there are some exceptions in manufacturing when multiple device could have same mac (like Arduino controllers). However, this is EXCEPTIONAL, rather than general

Get Bluetooth local mac address in Marshmallow

Pre Marshmallow my app would obtain it's device MAC address via BluetoothAdapter.getDefaultAdapter().getAddress().
Now with Marshmallow Android is returning 02:00:00:00:00:00.
I saw some link(sorry not sure where now) that said you need to add the additional permission
<uses-permission android:name="android.permission.LOCAL_MAC_ADDRESS"/>
to be able to get it. However it isn't working for me.
Is there some additional permission needed to get the mac address?
I am not sure it is pertinent here but the manifest also includes
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
So is there a way to get the local bluetooth mac address?
zmarties is right but you can still get the mac address via reflection or Settings.Secure:
String macAddress = android.provider.Settings.Secure.getString(context.getContentResolver(), "bluetooth_address");
Access to the mac address has been deliberately removed:
To provide users with greater data protection, starting in this release, Android removes programmatic access to the device’s local hardware identifier for apps using the Wi-Fi and Bluetooth APIs.
(from Android 6.0 Changes)
You can access Mac address from the file
"/sys/class/net/" + networkInterfaceName+ "/address" ,where networkInterfaceName can be wlan0 or eth1.But Its permission may be read-protected,so it may not work in some devices.
I am also attaching the code part which i got from SO.
public static String getWifiMacAddress() {
try {
String interfaceName = "wlan0";
List<NetworkInterface> interfaces = Collections
.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
if (!intf.getName().equalsIgnoreCase(interfaceName)) {
continue;
}
byte[] mac = intf.getHardwareAddress();
if (mac == null) {
return "";
}
StringBuilder buf = new StringBuilder();
for (byte aMac : mac) {
buf.append(String.format("%02X:", aMac));
}
if (buf.length() > 0) {
buf.deleteCharAt(buf.length() - 1);
}
return buf.toString();
}
} catch (Exception exp) {
exp.printStackTrace();
}
return "";
}
First the following permissions have to be added to Manifest;
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.LOCAL_MAC_ADDRESS" />
Then,
public static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS = "bluetooth_address";
String macAddress = Settings.Secure.getString(getContentResolver(), SECURE_SETTINGS_BLUETOOTH_ADDRESS);
After that the application has to be signed with OEM / System key. Tested and verified on Android 8.1.0.
Please use the below code to get the bluetooth mac address. let me know if any issues.
private String getBluetoothMacAddress() {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
String bluetoothMacAddress = "";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M){
try {
Field mServiceField = bluetoothAdapter.getClass().getDeclaredField("mService");
mServiceField.setAccessible(true);
Object btManagerService = mServiceField.get(bluetoothAdapter);
if (btManagerService != null) {
bluetoothMacAddress = (String) btManagerService.getClass().getMethod("getAddress").invoke(btManagerService);
}
} catch (NoSuchFieldException e) {
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
} else {
bluetoothMacAddress = bluetoothAdapter.getAddress();
}
return bluetoothMacAddress;
}
Getting the MAC address via reflection can look like this:
private static String getBtAddressViaReflection() {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Object bluetoothManagerService = new Mirror().on(bluetoothAdapter).get().field("mService");
if (bluetoothManagerService == null) {
Log.w(TAG, "couldn't find bluetoothManagerService");
return null;
}
Object address = new Mirror().on(bluetoothManagerService).invoke().method("getAddress").withoutArgs();
if (address != null && address instanceof String) {
Log.w(TAG, "using reflection to get the BT MAC address: " + address);
return (String) address;
} else {
return null;
}
}
using a reflection library (net.vidageek:mirror) but you'll get the idea.
Since below method return null for android O.
String macAddress = android.provider.Settings.Secure.getString(context.getContentResolver(), "bluetooth_address");
I found new way to get Bluetooth Mac address, you can try by using below command line.
su strings /data/misc/bluedroid/bt_config.conf | grep Address
NOTE: In my case, i was working with root device so my app has super user permission.
As it turns out, I ended up not getting the MAC address from Android. The bluetooth device ended up providing the Android device MAC address, which was stored and then used when needed. Yeah it seems a little funky but on the project I was on, the bluetooth device software was also being developed and this turned out to be the best way to deal with the situation.
Worked great
private String getBluetoothMacAddress() {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
String bluetoothMacAddress = "";
try {
Field mServiceField = bluetoothAdapter.getClass().getDeclaredField("mService");
mServiceField.setAccessible(true);
Object btManagerService = mServiceField.get(bluetoothAdapter);
if (btManagerService != null) {
bluetoothMacAddress = (String) btManagerService.getClass().getMethod("getAddress").invoke(btManagerService);
}
} catch (NoSuchFieldException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignore) {
}
return bluetoothMacAddress;
}

How we can check our App is running in real device or bluestack? [duplicate]

I would like to have my code run slightly differently when running on the emulator than when running on a device. (For example, using 10.0.2.2 instead of a public URL to run against a development server automatically.) What is the best way to detect when an Android application is running in the emulator?
How about this solution (class implementation of SystemProperties is available here):
val isProbablyRunningOnEmulator: Boolean by lazy {
// Android SDK emulator
return#lazy ((Build.MANUFACTURER == "Google" && Build.BRAND == "google" &&
((Build.FINGERPRINT.startsWith("google/sdk_gphone_")
&& Build.FINGERPRINT.endsWith(":user/release-keys")
&& Build.PRODUCT.startsWith("sdk_gphone_")
&& Build.MODEL.startsWith("sdk_gphone_"))
//alternative
|| (Build.FINGERPRINT.startsWith("google/sdk_gphone64_")
&& (Build.FINGERPRINT.endsWith(":userdebug/dev-keys") || Build.FINGERPRINT.endsWith(":user/release-keys"))
&& Build.PRODUCT.startsWith("sdk_gphone64_")
&& Build.MODEL.startsWith("sdk_gphone64_"))))
//
|| Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.MODEL.contains("google_sdk")
|| Build.MODEL.contains("Emulator")
|| Build.MODEL.contains("Android SDK built for x86")
//bluestacks
|| "QC_Reference_Phone" == Build.BOARD && !"Xiaomi".equals(Build.MANUFACTURER, ignoreCase = true)
//bluestacks
|| Build.MANUFACTURER.contains("Genymotion")
|| Build.HOST.startsWith("Build")
//MSI App Player
|| Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic")
|| Build.PRODUCT == "google_sdk"
// another Android SDK emulator check
|| SystemProperties.getProp("ro.kernel.qemu") == "1")
}
Note that some emulators fake exact specs of real devices, so it might be impossible to detect it. I've added what I could, but I don't think there is a 100% way to detect if it's really an emulator or not.
Here a tiny snippet you can make in the APK to show various things about it, so you could add your own rules:
textView.text = "FINGERPRINT:${Build.FINGERPRINT}\n" +
"MODEL:${Build.MODEL}\n" +
"MANUFACTURER:${Build.MANUFACTURER}\n" +
"BRAND:${Build.BRAND}\n" +
"DEVICE:${Build.DEVICE}\n" +
"BOARD:${Build.BOARD}\n" +
"HOST:${Build.HOST}\n" +
"PRODUCT:${Build.PRODUCT}\n"
One common one sems to be Build.FINGERPRINT.contains("generic")
Google uses this code in the device-info plugin from Flutter to determine if the device is an emulator:
private boolean isEmulator() {
return (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
|| Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.HARDWARE.contains("goldfish")
|| Build.HARDWARE.contains("ranchu")
|| Build.MODEL.contains("google_sdk")
|| Build.MODEL.contains("Emulator")
|| Build.MODEL.contains("Android SDK built for x86")
|| Build.MANUFACTURER.contains("Genymotion")
|| Build.PRODUCT.contains("sdk_google")
|| Build.PRODUCT.contains("google_sdk")
|| Build.PRODUCT.contains("sdk")
|| Build.PRODUCT.contains("sdk_x86")
|| Build.PRODUCT.contains("sdk_gphone64_arm64")
|| Build.PRODUCT.contains("vbox86p")
|| Build.PRODUCT.contains("emulator")
|| Build.PRODUCT.contains("simulator");
}
Well Android id does not work for me, I'm currently using:
"google_sdk".equals( Build.PRODUCT );
Based on hints from other answers, this is probably the most robust way:
isEmulator = "goldfish".equals(Build.HARDWARE)
How about something like the code below to tell if your app was signed with the debug key? it's not detecting the emulator but it might work for your purpose?
public void onCreate Bundle b ) {
super.onCreate(savedInstanceState);
if ( signedWithDebugKey(this,this.getClass()) ) {
blah blah blah
}
blah
blah
blah
}
static final String DEBUGKEY =
"get the debug key from logcat after calling the function below once from the emulator";
public static boolean signedWithDebugKey(Context context, Class<?> cls)
{
boolean result = false;
try {
ComponentName comp = new ComponentName(context, cls);
PackageInfo pinfo = context.getPackageManager().getPackageInfo(comp.getPackageName(),PackageManager.GET_SIGNATURES);
Signature sigs[] = pinfo.signatures;
for ( int i = 0; i < sigs.length;i++)
Log.d(TAG,sigs[i].toCharsString());
if (DEBUGKEY.equals(sigs[0].toCharsString())) {
result = true;
Log.d(TAG,"package has been signed with the debug key");
} else {
Log.d(TAG,"package signed with a key other than the debug key");
}
} catch (android.content.pm.PackageManager.NameNotFoundException e) {
return false;
}
return result;
}
This code works for me
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = tm.getNetworkOperatorName();
if("Android".equals(networkOperator)) {
// Emulator
}
else {
// Device
}
In case that device does not have sim card, It retuns empty string:""
Since Android emulator always retuns "Android" as network operator, I use above code.
I tried several techniques, but settled on a slightly revised version of checking the Build.PRODUCT as below. This seems to vary quite a bit from emulator to emulator, that's why I have the 3 checks I currently have. I guess I could have just checked if product.contains("sdk") but thought the check below was a bit safer.
public static boolean isAndroidEmulator() {
String model = Build.MODEL;
Log.d(TAG, "model=" + model);
String product = Build.PRODUCT;
Log.d(TAG, "product=" + product);
boolean isEmulator = false;
if (product != null) {
isEmulator = product.equals("sdk") || product.contains("_sdk") || product.contains("sdk_");
}
Log.d(TAG, "isEmulator=" + isEmulator);
return isEmulator;
}
FYI - I found that my Kindle Fire had Build.BRAND = "generic", and some of the emulators didn't have "Android" for the network operator.
Both the following are set to "google_sdk":
Build.PRODUCT
Build.MODEL
So it should be enough to use either one of the following lines.
"google_sdk".equals(Build.MODEL)
or
"google_sdk".equals(Build.PRODUCT)
I never found a good way to tell if you're in the emulator.
but if you just need to detecet if you're in a development environment you can do this :
if(Debug.isDebuggerConnected() ) {
// Things to do in debug environment...
}
Hope this help....
I just look for _sdk, _sdk_ or sdk_, or even just sdk part in Build.PRODUCT:
if(Build.PRODUCT.matches(".*_?sdk_?.*")){
//-- emulator --
}else{
//-- other device --
}
use this function :
public static final boolean isEmulator() {
int rating = 0;
if ((Build.PRODUCT.equals("sdk")) || (Build.PRODUCT.equals("google_sdk"))
|| (Build.PRODUCT.equals("sdk_x86")) || (Build.PRODUCT.equals("vbox86p"))) {
rating++;
}
if ((Build.MANUFACTURER.equals("unknown")) || (Build.MANUFACTURER.equals("Genymotion"))) {
rating++;
}
if ((Build.BRAND.equals("generic")) || (Build.BRAND.equals("generic_x86"))) {
rating++;
}
if ((Build.DEVICE.equals("generic")) || (Build.DEVICE.equals("generic_x86")) || (Build.DEVICE.equals("vbox86p"))) {
rating++;
}
if ((Build.MODEL.equals("sdk")) || (Build.MODEL.equals("google_sdk"))
|| (Build.MODEL.equals("Android SDK built for x86"))) {
rating++;
}
if ((Build.HARDWARE.equals("goldfish")) || (Build.HARDWARE.equals("vbox86"))) {
rating++;
}
if ((Build.FINGERPRINT.contains("generic/sdk/generic"))
|| (Build.FINGERPRINT.contains("generic_x86/sdk_x86/generic_x86"))
|| (Build.FINGERPRINT.contains("generic/google_sdk/generic"))
|| (Build.FINGERPRINT.contains("generic/vbox86p/vbox86p"))) {
rating++;
}
return rating > 4;
}
Don't know if there are better ways to detect the emu, but the emulator will have the file init.goldfish.rc in the root-directory.
It's the emulator specific startup-script, and it shouldn't be there on a non-emulator build.
Here is my solution (it works only if you run a web server on your debug machine):
I have created a background task that starts when the application starts. It looks for http://10.0.2.2 and if it exists it changes a global parameter (IsDebug) to true. It is a silent way to find out where you are running.
public class CheckDebugModeTask extends AsyncTask<String, Void, String> {
public static boolean IsDebug = false;
public CheckDebugModeTask()
{
}
#Override
protected String doInBackground(String... params) {
try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 2000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
String url2 = "http://10.0.2.2";
HttpGet httpGet = new HttpGet(url2);
DefaultHttpClient client = new DefaultHttpClient(httpParameters);
HttpResponse response2 = client.execute(httpGet);
if (response2 == null || response2.getEntity() == null || response2.getEntity().getContent() == null)
return "";
return "Debug";
} catch (Exception e) {
return "";
}
}
#Override
protected void onPostExecute (String result)
{
if (result == "Debug")
{
CheckDebugModeTask.IsDebug = true;
}
}
from the main activity onCreate:
CheckDebugModeTask checkDebugMode = new CheckDebugModeTask();
checkDebugMode.execute("");
From Battery, the emulator:
Power source is always AC Charger.
Temperature is always 0.
And you can use Build.HOST to record host value, different emulator has different host value.
Another option would be to look at the ro.hardware property and see if its set to goldfish. Unfortunately there doesn't seem to be an easy way to do this from Java but its trivial from C using property_get().
I found the new emulator Build.HARDWARE = "ranchu".
Reference:https://groups.google.com/forum/#!topic/android-emulator-dev/dltBnUW_HzU
And also I found the Android official way to check whether emulator or not.I think it's good reference for us.
Since Android API Level 23 [Android 6.0]
package com.android.internal.util;
/**
* #hide
*/
public class ScreenShapeHelper {
private static final boolean IS_EMULATOR = Build.HARDWARE.contains("goldfish");
}
We have ScreenShapeHelper.IS_EMULATOR to check whether emulator.
Since Android API Level 24 [Android 7.0]
package android.os;
/**
* Information about the current build, extracted from system properties.
*/
public class Build {
/**
* Whether this build was for an emulator device.
* #hide
*/
public static final boolean IS_EMULATOR = getString("ro.kernel.qemu").equals("1");
}
We have Build.IS_EMULATOR to check whether emulator.
The way the official to check whether emulator is not new,and also maybe not enough,the answers above also mentioned.
But this maybe show us that the official will provide the way of official to check whether emulator or not.
As using the above all ways mentioned,right now we can also use the two ways about to check whether emulator.
How to access the com.android.internal package and #hide
and wait for the official open SDK.
This is how Firebase Crashlytics approaches it:
private static final String GOLDFISH = "goldfish";
private static final String RANCHU = "ranchu";
private static final String SDK = "sdk";
public static boolean isEmulator() {
return Build.PRODUCT.contains(SDK)
|| Build.HARDWARE.contains(GOLDFISH)
|| Build.HARDWARE.contains(RANCHU);
}
The above suggested solution to check for the ANDROID_ID worked for me until I updated today to the latest SDK tools released with Android 2.2.
Therefore I currently switched to the following solution which works so far with the disadvantage however that you need to put the PHONE_STATE read permission (<uses-permission android:name="android.permission.READ_PHONE_STATE"/>)
private void checkForDebugMode() {
ISDEBUGMODE = false; //(Secure.getString(getApplicationContext().getContentResolver(), Secure.ANDROID_ID) == null);
TelephonyManager man = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
if(man != null){
String devId = man.getDeviceSoftwareVersion();
ISDEBUGMODE = (devId == null);
}
}
Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic")
This should return true if the app is running on an emulator.
What we should be careful about is not detecting all the emulators because there are only several different emulators. It is easy to check.
We have to make sure that actual devices are not detected as an emulator.
I used the app called "Android Device Info Share" to check this.
On this app, you can see various kinds of information of many devices (probably most devices in the world; if the device you are using is missing from the list, it will be added automatically).
All answers in one method
static boolean checkEmulator()
{
try
{
String buildDetails = (Build.FINGERPRINT + Build.DEVICE + Build.MODEL + Build.BRAND + Build.PRODUCT + Build.MANUFACTURER + Build.HARDWARE).toLowerCase();
if (buildDetails.contains("generic")
|| buildDetails.contains("unknown")
|| buildDetails.contains("emulator")
|| buildDetails.contains("sdk")
|| buildDetails.contains("genymotion")
|| buildDetails.contains("x86") // this includes vbox86
|| buildDetails.contains("goldfish")
|| buildDetails.contains("test-keys"))
return true;
}
catch (Throwable t) {Logger.catchedError(t);}
try
{
TelephonyManager tm = (TelephonyManager) App.context.getSystemService(Context.TELEPHONY_SERVICE);
String non = tm.getNetworkOperatorName().toLowerCase();
if (non.equals("android"))
return true;
}
catch (Throwable t) {Logger.catchedError(t);}
try
{
if (new File ("/init.goldfish.rc").exists())
return true;
}
catch (Throwable t) {Logger.catchedError(t);}
return false;
}
Checking the answers, none of them worked when using LeapDroid, Droid4x or Andy emulators,
What does work for all cases is the following:
private static String getSystemProperty(String name) throws Exception {
Class systemPropertyClazz = Class.forName("android.os.SystemProperties");
return (String) systemPropertyClazz.getMethod("get", new Class[]{String.class}).invoke(systemPropertyClazz, new Object[]{name});
}
public boolean isEmulator() {
boolean goldfish = getSystemProperty("ro.hardware").contains("goldfish");
boolean emu = getSystemProperty("ro.kernel.qemu").length() > 0;
boolean sdk = getSystemProperty("ro.product.model").equals("sdk");
return goldfish || emu || sdk;
}
My recommendation:
try this from github.
Easy to detect android emulator
Checked on real devices in Device Farm (https://aws.amazon.com/device-farm/)
BlueStacks
Genymotion
Android Emulator
Andy 46.2.207.0
MEmu play
Nox App Player
Koplayer
.....
How to use with an Example:
EmulatorDetector.with(this)
.setCheckTelephony(true)
.addPackageName("com.bluestacks")
.setDebug(true)
.detect(new EmulatorDetector.OnEmulatorDetectorListener() {
#Override
public void onResult(boolean isEmulator) {
if(isEmulator){
// Do your work
}
else{
// Not emulator and do your work
}
}
});
you can check the IMEI #,
http://developer.android.com/reference/android/telephony/TelephonyManager.html#getDeviceId%28%29
if i recall on the emulator this return 0. however, there's no documentation i can find that guarantees that. although the emulator might not always return 0, it seems pretty safe that a registered phone would not return 0. what would happen on a non-phone android device, or one without a SIM card installed or one that isn't currently registered on the network?
seems like that'd be a bad idea, to depend on that.
it also means you'd need to ask for permission to read the phone state, which is bad if you don't already require it for something else.
if not that, then there's always flipping some bit somewhere before you finally generate your signed app.
Actually, ANDROID_ID on 2.2 always equals 9774D56D682E549C (according to this thread + my own experiments).
So, you could check something like this:
String androidID = ...;
if(androidID == null || androidID.equals("9774D56D682E549C"))
do stuff;
Not the prettiest, but it does the job.
This works for me
public boolean isEmulator() {
return Build.MANUFACTURER.equals("unknown");
}
Put a file in the file system of the emulator; since the file won't exist on the real device, this should be stable, reliable and easy to fix when it breaks.
I've collected all the answers on this question and came up with function to detect if Android is running on a vm/emulator:
public boolean isvm(){
StringBuilder deviceInfo = new StringBuilder();
deviceInfo.append("Build.PRODUCT " +Build.PRODUCT +"\n");
deviceInfo.append("Build.FINGERPRINT " +Build.FINGERPRINT+"\n");
deviceInfo.append("Build.MANUFACTURER " +Build.MANUFACTURER+"\n");
deviceInfo.append("Build.MODEL " +Build.MODEL+"\n");
deviceInfo.append("Build.BRAND " +Build.BRAND+"\n");
deviceInfo.append("Build.DEVICE " +Build.DEVICE+"\n");
String info = deviceInfo.toString();
Log.i("LOB", info);
Boolean isvm = false;
if(
"google_sdk".equals(Build.PRODUCT) ||
"sdk_google_phone_x86".equals(Build.PRODUCT) ||
"sdk".equals(Build.PRODUCT) ||
"sdk_x86".equals(Build.PRODUCT) ||
"vbox86p".equals(Build.PRODUCT) ||
Build.FINGERPRINT.contains("generic") ||
Build.MANUFACTURER.contains("Genymotion") ||
Build.MODEL.contains("Emulator") ||
Build.MODEL.contains("Android SDK built for x86")
){
isvm = true;
}
if(Build.BRAND.contains("generic")&&Build.DEVICE.contains("generic")){
isvm = true;
}
return isvm;
}
Tested on Emulator, Genymotion and Bluestacks (1 October 2015).
Whichever code you use to do emulator detection, I'd highly recommend writing unit tests to cover all the Build.FINGERPRINT, Build.HARDWARE and Build.MANUFACTURER values that you are depending on. Here are some example tests:
#Test
public void testIsEmulatorGenymotion() throws Exception {
assertThat(
DeviceUtils.isRunningOnEmulator(
"generic/vbox86p/vbox86p:4.1.1/JRO03S/eng.buildbot.20150217.102902:userdebug/test-keys",
"vbox86", "Genymotion")).isTrue();
assertThat(
DeviceUtils.isRunningOnEmulator(
"generic/vbox86p/vbox86p:5.1/LMY47D/buildbot06092001:userdebug/test-keys", "vbox86",
"Genymotion")).isTrue();
}
#Test
public void testIsEmulatorDefaultAndroidEmulator() throws Exception {
assertThat(
DeviceUtils.isRunningOnEmulator(
"generic_x86/sdk_google_phone_x86/generic_x86:5.0.2/LSY66H/1960483:eng/test-keys", "goldfish",
"unknown")).isTrue();
assertThat(
DeviceUtils.isRunningOnEmulator(
"Android/sdk_google_phone_x86_64/generic_x86_64:6.0/MASTER/2469028:userdebug/test-keys",
"ranchu", "unknown")).isTrue();
}
#Test
public void testIsEmulatorRealNexus5() throws Exception {
assertThat(
DeviceUtils.isRunningOnEmulator("google/hammerhead/hammerhead:6.0.1/MMB29K/2419427:user/release-keys",
"hammerhead", "LGE")).isFalse();
}
...and here's our code (debug logs and comments removed for conciseness):
public static boolean isRunningOnEmulator() {
if (sIsRunningEmulator == null) {
sIsRunningEmulator = isRunningOnEmulator(Build.FINGERPRINT, Build.HARDWARE, Build.MANUFACTURER);
}
return sIsRunningEmulator;
}
static boolean isRunningOnEmulator(String fingerprint, String hardware, String manufacturer) {
boolean isEmulatorFingerprint = fingerprint.endsWith("test-keys");
boolean isEmulatorManufacturer = manufacturer.equals("Genymotion")
|| manufacturer.equals("unknown");
if (isEmulatorFingerprint && isEmulatorManufacturer) {
return true;
} else {
return false;
}
}
Another option is to check if you are in debug mode or production mode:
if (BuildConfig.DEBUG) { Log.i(TAG, "I am in debug mode"); }
simple and reliable.
Not totally the answer of the question but in most cases you may want to distinguish between debugging/test sessions and life sessions of your user base.
In my case I set google analytics to dryRun() when in debug mode so this approach works totally fine for me.
For more advanced users there is another option. gradle build variants:
in your app's gradle file add a new variant:
buildTypes {
release {
// some already existing commands
}
debug {
// some already existing commands
}
// the following is new
test {
}
}
In your code check the build type:
if ("test".equals(BuildConfig.BUILD_TYPE)) { Log.i(TAG, "I am in Test build type"); }
else if ("debug".equals(BuildConfig.BUILD_TYPE)) { Log.i(TAG, "I am in Debug build type"); }
Now you have the opportunity to build 3 different types of your app.

Android: Get the device name programmatically

This is what I tried.
mTextView.setText("MODEL: "+android.os.Build.MODEL
+"\nDEVICE: "+android.os.Build.DEVICE
+"\nBRAND: "+android.os.Build.BRAND
+"\nDISPLAY: "+android.os.Build.DISPLAY
+"\nBOARD: "+android.os.Build.BOARD
+"\nHOST: "+android.os.Build.HOST
+"\nMANUFACTURER: "+android.os.Build.MANUFACTURER
+"\nPRODUCT: "+android.os.Build.PRODUCT);
Can anyone tell me how to get these outputs:
Samsung Galaxy S
Samsung note 3
Sony Xperia z
Sony Xperai z1
Samsung Grand
for nexus it shows nexus 4 or nexus 7 not the same case with sony or samsung.
you can use:
public String getDeviceName() {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
if (model.startsWith(manufacturer)) {
return capitalize(model);
} else {
return capitalize(manufacturer) + " " + model;
}
}
private String capitalize(String s) {
if (s == null || s.length() == 0) {
return "";
}
char first = s.charAt(0);
if (Character.isUpperCase(first)) {
return s;
} else {
return Character.toUpperCase(first) + s.substring(1);
}
}
see this for Build.MODEL.
more info in Get Android Phone Model Programmatically.
In order to get android device name you have to add only a single line of code:
android.os.Build.MODEL;
Found here:getting-android-device-name
Download csv from here:
https://support.google.com/googleplay/answer/1727131?hl=en
See if your device works with Google Play by checking the list below.
When you download the PDF file, devices are ordered alphabetically
(A-Z) by manufacturer name.
Then import this file into your database.
Query RetailBranding and Marketing Name by Model = Build.Model.
To have a better performance, put these data in your database server.
Get the RetailBranding and Marketing Name when the app is first launched and save it to the local database.
you can also get it via bluetoothAdapter see this
public String getPhoneName()
{
BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter();
String deviceName = myDevice.getName();
return deviceName;
}

How to find MAC address of an Android device programmatically

How do i get Mac Id of android device programmatically. I have done with IMIE Code and I know how to check Mac id on device manually but have no idea how to find out programmatically.
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String macAddress = wInfo.getMacAddress();
Also, add below permission in your manifest file
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Please refer to Android 6.0 Changes.
To provide users with greater data protection, starting in this release, Android removes programmatic access to the device’s local hardware identifier for apps using the Wi-Fi and Bluetooth APIs. The WifiInfo.getMacAddress() and the BluetoothAdapter.getAddress() methods now return a constant value of 02:00:00:00:00:00.
To access the hardware identifiers of nearby external devices via Bluetooth and Wi-Fi scans, your app must now have the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permissions.
See this post where I have submitted Utils.java example to provide pure-java implementations and works without WifiManager. Some android devices may not have wifi available or are using ethernet wiring.
Utils.getMACAddress("wlan0");
Utils.getMACAddress("eth0");
Utils.getIPAddress(true); // IPv4
Utils.getIPAddress(false); // IPv6
With this code you will be also able to get MacAddress in Android 6.0 also
public static String getMacAddr() {
try {
List <NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif: all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder res1 = new StringBuilder();
for (byte b: macBytes) {
//res1.append(Integer.toHexString(b & 0xFF) + ":");
res1.append(String.format("%02X:", b));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {}
return "02:00:00:00:00:00";
}
EDIT 1.
This answer got a bug where a byte that in hex form got a single digit, will not appear with a "0" before it. The append to res1 has been changed to take care of it.
It's Working
package com.keshav.fetchmacaddress;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("keshav","getMacAddr -> " +getMacAddr());
}
public static String getMacAddr() {
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
// res1.append(Integer.toHexString(b & 0xFF) + ":");
res1.append(String.format("%02X:",b));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
//handle exception
}
return "";
}
}
UPDATE 1
This answer got a bug where a byte that in hex form got a single digit, will not appear with a "0" before it. The append to res1 has been changed to take care of it.
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
// res1.append(Integer.toHexString(b & 0xFF) + ":");
res1.append(String.format("%02X:",b));
}
Recent update from Developer.Android.com
Don't work with MAC addresses MAC addresses are globally unique, not
user-resettable, and survive factory resets. For these reasons, it's
generally not recommended to use MAC address for any form of user
identification. Devices running Android 10 (API level 29) and higher
report randomized MAC addresses to all apps that aren't device owner
apps.
Between Android 6.0 (API level 23) and Android 9 (API level 28), local
device MAC addresses, such as Wi-Fi and Bluetooth, aren't available
via third-party APIs. The WifiInfo.getMacAddress() method and the
BluetoothAdapter.getDefaultAdapter().getAddress() method both return
02:00:00:00:00:00.
Additionally, between Android 6.0 and Android 9, you must hold the
following permissions to access MAC addresses of nearby external
devices available via Bluetooth and Wi-Fi scans:
Method/Property Permissions Required
ACCESS_FINE_LOCATION or
ACCESS_COARSE_LOCATION
Source: https://developer.android.com/training/articles/user-data-ids.html#version_specific_details_identifiers_in_m
Here the Kotlin version of Arth Tilvas answer:
fun getMacAddr(): String {
try {
val all = Collections.list(NetworkInterface.getNetworkInterfaces())
for (nif in all) {
if (!nif.getName().equals("wlan0", ignoreCase=true)) continue
val macBytes = nif.getHardwareAddress() ?: return ""
val res1 = StringBuilder()
for (b in macBytes) {
//res1.append(Integer.toHexString(b & 0xFF) + ":");
res1.append(String.format("%02X:", b))
}
if (res1.length > 0) {
res1.deleteCharAt(res1.length - 1)
}
return res1.toString()
}
} catch (ex: Exception) {
}
return "02:00:00:00:00:00"
}
private fun getMac(): String? =
try {
NetworkInterface.getNetworkInterfaces()
.toList()
.find { networkInterface -> networkInterface.name.equals("wlan0", ignoreCase = true) }
?.hardwareAddress
?.joinToString(separator = ":") { byte -> "%02X".format(byte) }
} catch (ex: Exception) {
ex.printStackTrace()
null
}
There is a simple way:
Android:
String macAddress =
android.provider.Settings.Secure.getString(this.getApplicationContext().getContentResolver(), "android_id");
Xamarin:
Settings.Secure.GetString(this.ContentResolver, "android_id");

Categories

Resources