kathak
kathak

Reputation: 1

Android Bluetooth - service to log nearby bluetooth devices

Is it possible to create a service that can listen for devices nearby and log device info to a file?

Upvotes: 0

Views: 889

Answers (2)

Tom
Tom

Reputation: 17892

Yes, your service can listen for new Bluetooth devices, as described by Vipul Shah, but the real issue is how do you cause your device to find other Bluetooth devices in the first place.

ACTION_FOUND is sent when a remote device is found during discovery. You can call BluetoothAdapter.startDiscovery() to start the discovery process, but the problem is that very few devices are normally discoverable. A couple of years ago it was common for devices to remain discoverable all the time, but now the user is expected to make a device temporarily discoverable as needed to pair it.

So, it doesn't make sense to have a service that periodically does discovery (and listen for ACTION_FOUND) both because it consumes a lot of battery and because you won't find anything.

If you know the Bluetooth address of the devices that you are looking for then you could try to connect to them, but I assume that is not the case.

Upvotes: 1

Vipul
Vipul

Reputation: 28103

Yes it is very much possible

Step 1 You will need to create one service

Step 2 You will need BluetoothDevice.ACTION_FOUND Broadcast Receiver to look for nearby devices.

Step 3 Then you can query all found devices one by one.

Step 4 As you will fast enumerate over found devices dump their information inside file.

Below is broadcast Receiver

 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // Add the name and address to an array adapter to show in a ListView
                // You will log this information into file.
                mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            }
        }
    };

Register the broadcast receiver for intent action as follows

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

Hope this helps.

Upvotes: 0

Related Questions