Get Bluetooth local mac address in Marshmallow - android

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;
}

Related

getMacAddress() returns null in Android 11? How to get mac address for Android 11?

{
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) {
macTestResultString = "";
}
}
} catch (Exception ex) {
Log.e(App.TAG, EXCEPTION + ex.getMessage());
}
return macTestResultString;
}
Getting mac address on device api more than 10 is almost impossible. Android's new security restriction no longer allow to access mac address read here.
Why do you need the mac address mention the reason might be there is some other solution that may help.

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

Can one programmatically obtain the MAC address of a device running Android 6.0+?

Can one programmatically obtain the MAC address of a device running Android 6.0+?
According to this,
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.
Does that mean it's impossible to get the device's MAC address in Android 6.0+? If it's possible, can you tell me how to do it in Android Studio?
Also, this answer only applies to devices with versions of Android below 6.0
You can use an alternative way to get the MAC addr on a Android 6.0 device.
First add Internet User-Permission to your AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Secondly,
try {
// get all the interfaces
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
//find network interface wlan0
for (NetworkInterface networkInterface : all) {
if (!networkInterface.getName().equalsIgnoreCase("wlan0")) continue;
//get the hardware address (MAC) of the interface
byte[] macBytes = networkInterface.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
//gets the last byte of b
res1.append(Integer.toHexString(b & 0xFF) + ":");
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
ex.printStackTrace();
}

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");

How to detect WiFi tethering state

I want to know how to detect state of WiFi tethering. I've seen an article: Android 2.3 wifi hotspot API But it doesn't work! It returns always WIFI_AP_STATE_DISABLED = 1. It doesn't depend on real state of WiFi tethering.
Using reflection:
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
Method[] wmMethods = wifi.getClass().getDeclaredMethods();
for (Method method: wmMethods) {
if (method.getName().equals("isWifiApEnabled")) {
try {
boolean isWifiAPenabled = method.invoke(wifi);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
As you can see here
In addition to the reflexion, to get the Wifi tethering status update, you can listen to this broadcast Action :
IntentFilter filter = new IntentFilter("android.net.wifi.WIFI_AP_STATE_CHANGED");
To get all tethering option update :
IntentFilter filter = new IntentFilter("android.net.conn.TETHER_STATE_CHANGED");
Those actions are hidden inside the Android source code
First, you need to get WifiManager:
Context context = ...
final WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Then:
public static boolean isSharingWiFi(final WifiManager manager)
{
try
{
final Method method = manager.getClass().getDeclaredMethod("isWifiApEnabled");
method.setAccessible(true); //in the case of visibility change in future APIs
return (Boolean) method.invoke(manager);
}
catch (final Throwable ignored)
{
}
return false;
}
Also you need to request a permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Here is the Xamarin C# version if anyone is looking:
static Method isWifiApEnabledMethod;
public static bool IsWifiApEnabled ()
{
var wifiManager = WifiManager.FromContext (Application.Context);
if (isWifiApEnabledMethod == null)
{
try
{
isWifiApEnabledMethod = wifiManager.Class.GetDeclaredMethod ("isWifiApEnabled");
isWifiApEnabledMethod.Accessible = true; //in the case of visibility change in future APIs
}
catch (NoSuchMethodException e)
{
Debug.WriteLine ("Can't get method by reflection" + e);
}
catch (System.Exception ex)
{
Debug.WriteLine ("Can't get method by reflection" + ex);
}
}
if (isWifiApEnabledMethod != null)
{
try
{
return (bool)isWifiApEnabledMethod.Invoke (wifiManager);
}
catch (System.Exception ex)
{
Debug.WriteLine ("Can't invoke by reflection" + ex);
}
}
return false;
}
(without using reflection since they say google is restricting it)
I'm writting this answer 10 years later. also I don't know if this can be considered a good aproach or not but I first get the Wlan network interface IPs
and if there is no address I assume that it tethering isn't enabled. if there is an address, I check using the connectivity manger whether WI-FI is connected to a network or not. if there is an IP for the Wlan network interface but it isn't connected to a network, I assume tethering is enabled.
you probably would need to add this line to your manifest file
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
code to get the ip of an inteface (this only gets the IPv4, you can modify it to get the IPv6 or both if you want)
// method used to retrieve Wlan ip addresses IPv4 of the device.
public static String IpAddresses() throws NoAddressFoundException, SocketException {
Enumeration<NetworkInterface> Nics = NetworkInterface.getNetworkInterfaces();
while (Nics.hasMoreElements()) {
NetworkInterface NIC = Nics.nextElement();
if (NIC.isUp() && !NIC.isLoopback() && NIC.getName().contains("wlan")) {
Enumeration<InetAddress> Addresses = NIC.getInetAddresses();
while (Addresses.hasMoreElements()) {
InetAddress WlanAddress = Addresses.nextElement();
if (WlanAddress instanceof Inet4Address)
return WlanAddress.getHostAddress();
}
}
}
throw new NoAddressFoundException("No suitable wifi address found");
}
then if there is an address i check if wifi is connected by this method:
//method to check if the device is connected to a Wi-Fi network; it doesn't matter if network has access to internet
public static boolean isWifiConnected(Context context) {
ConnectivityManager ConMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo WifiInfo = ConMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return WifiInfo.isConnected();
}
NOTE: the "NoAddressFoundException" is a custom exception in my app if anyone is wondering. it won't exist in your case.
Reflection is a poor way to achieve this.
We can inspect the DhcpInfo to determine if the device is allocating addresses (mobile hotspot) or is being allocated by another DHCP server.
Here is a kotlin function that will determine if a device is a mobile hotspot, it has not been widely tested so YMMV.
fun isMobileHotspot(manager: WifiManager): Boolean {
val info = manager.dhcpInfo
return (
info.ipAddress == 0
&& info.netmask == 0
&& info.gateway == 0
&& info.serverAddress == 16885952) // 192.168.1.1
}

Categories

Resources