Android广播接收器蓝牙事件捕捉

Lon*_*ith 19 android bluetooth android-broadcast android-bluetooth

我正试图用广播接收器捕捉蓝牙状态变化.

我的清单:

<uses-permission android:name="android.permission.BLUETOOTH" />
<application>
     <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name=".BluetoothBroadcastReceiver"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
            <action android:name="android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED" />
            <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
            <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
        </intent-filter>
    </receiver>
</application>
Run Code Online (Sandbox Code Playgroud)

接收onReceive方法:

public void onReceive(Context context, Intent intent) {

    String action = intent.getAction();
    Log.d("BroadcastActions", "Action "+action+"received");
    int state;
    BluetoothDevice bluetoothDevice;

    switch(action)
    {
        case BluetoothAdapter.ACTION_STATE_CHANGED:
            state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
            if (state == BluetoothAdapter.STATE_OFF)
            {
                Toast.makeText(context, "Bluetooth is off", Toast.LENGTH_SHORT).show();
                Log.d("BroadcastActions", "Bluetooth is off");
            }
            else if (state == BluetoothAdapter.STATE_TURNING_OFF)
            {
                Toast.makeText(context, "Bluetooth is turning off", Toast.LENGTH_SHORT).show();
                Log.d("BroadcastActions", "Bluetooth is turning off");
            }
            else if(state == BluetoothAdapter.STATE_ON)
            {
                Log.d("BroadcastActions", "Bluetooth is on");
            }
            break;

        case BluetoothDevice.ACTION_ACL_CONNECTED:
            bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            Toast.makeText(context, "Connected to "+bluetoothDevice.getName(),
                    Toast.LENGTH_SHORT).show();
            Log.d("BroadcastActions", "Connected to "+bluetoothDevice.getName());
            break;

        case BluetoothDevice.ACTION_ACL_DISCONNECTED:
            bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            Toast.makeText(context, "Disconnected from "+bluetoothDevice.getName(),
                    Toast.LENGTH_SHORT).show();
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

我启动app然后按Home键将其最小化.转到设置并打开蓝牙但没有任何反应.虽然我期待吐司和logcat消息.这有什么不对?

Mus*_*tlu 46

为了赶上蓝牙状态变化(STATE_OFF,STATE_TURNING_ON,STATE_ON,STATE_TURNING_OFF),在您的活动做到这一点:

首先,为您的AndroidManifest文件添加蓝牙权限:

<uses-permission android:name="android.permission.BLUETOOTH" />
Run Code Online (Sandbox Code Playgroud)

在您的活动或服务中创建BroadcastReceiver:

    private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
            switch(state) {
                case BluetoothAdapter.STATE_OFF:
                    ..
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    ..
                    break;
                case BluetoothAdapter.STATE_ON:
                    ..
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    ..
                    break;
            }

        }
    }
};
Run Code Online (Sandbox Code Playgroud)

创建一个IntentFilter并在您的onCreate()方法中将BroadcastReceiver注册到Activity/Service :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    IntentFilter filter1 = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(mBroadcastReceiver1, filter1);

    ...
}
Run Code Online (Sandbox Code Playgroud)

onDestroy()方法中取消注册BroadcastReceiver :

@Override
protected void onDestroy() {
    super.onDestroy();

    unregisterReceiver(mBroadcastReceiver1);
}
Run Code Online (Sandbox Code Playgroud)

为了捕捉设备(的可发现的变化SCAN_MODE_NONE,SCAN_MODE_CONNECTABLE,SCAN_MODE_CONNECTABLE_DISCOVERABLE),创建另一广播接收器和正如我上面提到注册/注销到您的活性的影响.这些BroadcastReceiver之间的区别仅在于第一个使用BluetoothAdapter.EXTRA_STATE而另一个使用BluetoothAdapter.EXTRA_SCAN_MODE.以下是BroadcastReceiver捕获可发现性更改的示例代码:

创建过滤器并在onCreate()方法中注册:

IntentFilter filter2 = new IntentFilter();
filter2.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter2.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter2.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(mBroadcastReceiver2, filter2);
Run Code Online (Sandbox Code Playgroud)

在Activity/Service中创建BroadcastReciver以捕获可发现性更改:

    private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if(action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {

            int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);

            switch(mode){
                case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
                    ..
                    break;
                case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
                    ..
                    break;
                case BluetoothAdapter.SCAN_MODE_NONE:
                    ..
                    break;
            }
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

最后取消注册onDestroy():

unregisterReceiver(mBroadcastReceiver2);
Run Code Online (Sandbox Code Playgroud)

请注意,您不需要添加任何<intent-filter><receiver>AndroidManifest文件,除非您需要添加蓝牙权限.

如果你想赶上(ACTION_ACL_CONNECTED,ACTION_ACL_DISCONNECTED,ACTION_ACL_DISCONNECT_REQUESTED),现在你需要将添加<intent-filter>到您的AndroidManifest文件:

<intent-filter>
    <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
    <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
</intent-filter>
Run Code Online (Sandbox Code Playgroud)

创建过滤器并在onCreate()方法中注册:

IntentFilter filter3 = new IntentFilter();
filter3.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter3.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
registerReceiver(mBroadcastReceiver3, filter3);
Run Code Online (Sandbox Code Playgroud)

然后在Activity/Service中创建BroadcastReceiver:

    private final BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        switch (action){
            case BluetoothDevice.ACTION_ACL_CONNECTED:
                ..
                break;
            case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                ..
                break;
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

最后,取消注册:

unregisterReceiver(mBroadcastReceiver3);
Run Code Online (Sandbox Code Playgroud)

如果您想了解有关状态常量的更多信息,请参阅以下文档:

public static final String EXTRA_STATE:

在ACTION_STATE_CHANGED意图中用作int额外字段以请求当前电源状态.可能的值有:STATE_OFF,STATE_TURNING_ON,STATE_ON,STATE_TURNING_OFF

public static final String EXTRA_SCAN_MODE:

用作ACTION_SCAN_MODE_CHANGED意图中的int额外字段以请求当前扫描模式.可能的值有:SCAN_MODE_NONE,SCAN_MODE_CONNECTABLE,SCAN_MODE_CONNECTABLE_DISCOVERABLE

  • https://developer.android.com/guide/components/broadcasts.html#receiving_broadcasts:“从Android 8.0(API级别26)开始,系统对清单声明的接收者施加了额外的限制。如果您的应用程序针对API级别26或更高的级别,您不能使用清单为大多数隐式广播(不专门针对您的应用的广播)声明接收方。” (3认同)