I am sending an image via bluetooth in android and want to fetch the MAC address of Device to which the image is being sent.
Please find below my code.
private void bluetoothadd(){
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
Log.e("Bluetooth ","not found");
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBtIntent);
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
Log.e("Mac Addressess","are: "+mBluetoothAdapter.getRemoteDevice(device.getAddress()));
}
}
}
}
I am getting all paired device's MAC Address. I want the MAC Address of a device only to which data is being transmitted.
Use this:
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
When the intent is fired to connect to the remote device and the device is successfully established the Device Address is returned as extra data with the Flag EXTRA_DEVICE_ADDRESS
.
You can check for the connection and establish it
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
You can check the activity in the on onActivityResult
function to find the address like this
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
String add = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
address= add.toString();
// Get the BluetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
}
break;
}
}
This trick is used in the Bluetooth Chat Sample application you can find in the Examples folder of the SDK
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With