如何接收蓝牙设备工作的意图?

时间:2014-01-22 22:02:32

标签: android android-bluetooth

我正在尝试让我的应用程序的服务侦听蓝牙连接和断开连接尝试,因此我可以动态检查/支持蓝牙网络共享网络通信。

首先,我有两个三星S4(运行CyanogenMod 10.2,基于Android 4.3.1),我可以很好地配对。如果我将一台设备设置为蓝牙系绳,当另一台设备连接时,会创建一个新的bt-pan网络接口,并使用DHCP分配IP。我在shell中使用iwconfig和ifconfig确认了这一点。

我的应用程序中有以下权限:(还有更多,我只是指出我添加的BT权限)

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

这是我的服务onCreate,我设置了我的IntentFilters :(注意我在这里有Toasts,但我最初使用的是Logging)

@Override
public void onCreate() {
    super.onCreate();
    ...     
    this.mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);

    mLocalBroadcastManager.registerReceiver(mMessageReceiver, filter);
}

这是我的BroadcastReceiver实现:

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(action.equals(BluetoothDevice.ACTION_FOUND)) {
            Toast.makeText(getApplicationContext(), "BT found", Toast.LENGTH_SHORT).show();
        } else if(action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
            Toast.makeText(getApplicationContext(), "BT Connected", 
        } else if(action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
            Toast.makeText(getApplicationContext(), "BT Disconnected", Toast.LENGTH_SHORT).show();
        } else
            Toast.makeText(getApplicationContext(), "BT Disconnect requested", Toast.LENGTH_SHORT).show();
        }
    }
}

现在,当我关闭/打开蓝牙时,连接/断开配对设备,什么都不会触发。我已经用两端的设备付钱了。什么都没有播出。

有人有建议吗?我真的需要接收这些蓝牙事件。请不要指向具有相同权限和意图过滤器的其他帖子/网站。感谢。

2 个答案:

答案 0 :(得分:2)

我有一个非常相似的代码可行,我找到的唯一主要区别是:

mLocalBroadcastManager.registerReceiver(mMessageReceiver, filter);

我相信 registerReceiver 应该从上下文中调用>。 尝试从this调用该方法。即删除mLocalBroadcastManager之类的:

registerReceiver(mMessageReceiver, filter);

答案 1 :(得分:1)

如果您在清单上注册接收者而不是活动,即使您没有打开应用,也可以接收广播,您可以这样做:

    <receiver android:name=".BluetoothReceiver" >
        <intent-filter>
            <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
            <action android:name="android.bluetooth.device.action.BOND_STATE_CHANGED" />
        </intent-filter>
    </receiver>