Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get MAC Address of bluetooth connected device in android

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.

like image 908
Anchit Mittal Avatar asked Oct 11 '13 10:10

Anchit Mittal


2 Answers

Use this:

BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
like image 71
hitesh Avatar answered Sep 29 '22 00:09

hitesh


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 onActivityResultfunction 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

like image 20
Shiva Avatar answered Sep 28 '22 23:09

Shiva