Search code examples
androidbluetoothandroid-4.0-ice-cream-sandwich

Detect bluetooth connection (android sdk ICS)


I want to build a small App that will recognize any Bluetooth headset connection and disconnection and write it to log file.

I tried to use android SDK example for detecting Bluetooth connection but it's not working. When my application is loading I am getting a call to OnServiceConnected and that's about it. no other calls to OnServiceConnected or to OnServiceDisconnected when i am connecting and disconnecting by Bluetooth headsets (I tired more then one).

I wrote all the code in the OnCreate function.

Maybe the problem is with android 4? Or is it anything else?

// Get the default adapter
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

// Establish connection to the proxy.
mBluetoothAdapter.getProfileProxy(this.getApplicationContext(), mProfileListener, BluetoothProfile.HEADSET);

private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
    public void onServiceConnected(int profile, BluetoothProfile proxy) {
       // Write to log - OnServiceConnected
    }
    public void onServiceDisconnected(int profile) {
       // Write to log - OnServiceDisconnected 
    }
};

Solution

  • Ok, found it.

    Here is it:

    getApplicationContext().registerReceiver(receiver,
                        new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
    getApplicationContext().registerReceiver(receiver,
                        new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
    
    private final BroadcastReceiver mReceiver = new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context context, Intent intent)
            {
                if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action))
                {
                    // LOG - Connected
                }
                else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action))
                {
                    // LOG - Disconnected
                }
            }
        }