Bluetooth or other external protocols in Android emulator

Developing Android application that works with Bluetooth device can be tricky. Emulator does not support real Bluetooth, and even if it would, Bluetooth protocols can be difficult to follow when debugging. That's why it is good to abstract it when developing. One of the easiest and most flexible abstraction in Android for this - intents. It is particularly useful if your BLE device acts like data logger.

First, create BroadcastReceiver:

public class BluetoothReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String task = intent.getStringExtra("task");
        if (task.equals("BLE")) {
            final int val = intent.getIntExtra("val", -1);
            ...

Then initialize it from Activity:

BroadcastReceiver br = new BluetoothReceiver();
IntentFilter filter = new IntentFilter("ble.test");
this.registerReceiver(br, filter);

After that you can just send data from command line, manually or via predefined scripts, for example:

adb shell am broadcast -a ble.test --ei val 10 --es task BLE

And this is good not only for Bluetooth, but any external communication.

Comments