1

我想构建一个小应用程序,它将识别任何蓝牙耳机连接和断开连接并将其写入日志文件。

我尝试使用android SDK 示例来检测蓝牙连接,但它不起作用。当我的应用程序正在加载时,我收到了对 OnServiceConnected 的调用,仅此而已。当我通过蓝牙耳机连接和断开连接时,没有其他对 OnServiceConnected 或 OnServiceDisconnected 的呼叫(我累了不止一个)。

我在 OnCreate 函数中编写了所有代码。

也许问题出在android 4上?或者是别的什么?

// 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 
    }
};
4

1 回答 1

3

好的,找到了。

就这个:

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
            }
        }
    }
于 2012-04-17T13:53:31.043 回答