Android 广播接收器蓝牙事件捕捉 [英] Android Broadcast Receiver bluetooth events catching

查看:33
本文介绍了Android 广播接收器蓝牙事件捕捉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用广播接收器捕捉蓝牙状态的变化.

I'm trying to catch bluetooth state changes with Broadcast Receiver.

我的清单:

<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>

接收方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;
    }
}

我启动应用程序,然后按主页按钮将其最小化.转到设置并打开蓝牙,但没有任何反应.虽然我期待 toast 和 logcat 消息.这里有什么问题?

I launch app then minimize it by pressing Home button. Go to settings and turn on bluetooth but nothing happens. Though I expect toast and logcat messages. What's wrong here?

推荐答案

为了捕捉蓝牙状态变化 (STATE_OFF, STATE_TURNING_ON, STATE_ON>, STATE_TURNING_OFF),这样做:

In order to catch Bluetooth state changes (STATE_OFF, STATE_TURNING_ON, STATE_ON, STATE_TURNING_OFF), do this:

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

First, add Bluetooth permission to your AndroidManifest file:

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

在您的活动或服务中创建一个广播接收器:

Create a BroadcastReceiver in your Activity or Service:

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

        }
    }
};

创建一个 IntentFilter 并在您的活动/服务的 onCreate() 方法中使用 BroadcastReceiver 注册它:

Create an IntentFilter and register it with BroadcastReceiver in your Activity/Service's onCreate() method:

@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);
    
    ...
}

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

Unregister BroadcastReceiver in your onDestroy() method:

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

    unregisterReceiver(mBroadcastReceiver1);
}

为了捕捉设备可发现性的变化(SCAN_MODE_NONESCAN_MODE_CONNECTABLESCAN_MODE_CONNECTABLE_DISCOVERABLE),创建另一个 BroadcastReceiver 并注册/取消注册到您的活动正如我上面提到的.这些广播接收器之间的唯一区别是第一个使用 BluetoothAdapter.EXTRA_STATE,另一个使用 BluetoothAdapter.EXTRA_SCAN_MODE.以下是 BroadcastReceiver 捕获可发现性更改的示例代码:

In order to catch changes of discoverability of device (SCAN_MODE_NONE, SCAN_MODE_CONNECTABLE, SCAN_MODE_CONNECTABLE_DISCOVERABLE), create another BroadcastReceiver and register/unregister to your Activity as I mentioned above. Only difference between those BroadcastReceivers is the first one uses BluetoothAdapter.EXTRA_STATE and the other one uses BluetoothAdapter.EXTRA_SCAN_MODE. Here is the example code for BroadcastReceiver to catch discoverability changes:

创建一个 IntentFilter 并在 onCreate() 方法中注册它:

Create an IntentFilter and register it in onCreate() method:

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);

在 Activity/Service 中创建 BroadcastReciver 以捕捉可发现性变化:

Create the BroadcastReciver in Activity/Service to catch discoverability changes:

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

最后在onDestroy()中注销BroadcastReciver:

And lastly unregister BroadcastReciver in onDestroy():

unregisterReceiver(mBroadcastReceiver2);

请注意,您不需要在 AndroidManifest 文件中添加任何 ,除非您需要添加蓝牙当然允许.

Note that, you don't need to add any <intent-filter> or <receiver> to your AndroidManifest file, except you need to add Bluetooth permission of course.

如果你想捕捉 (ACTION_ACL_CONNECTED, ACTION_ACL_DISCONNECTED, ACTION_ACL_DISCONNECT_REQUESTED),现在你需要添加一个 到您的 AndroidManifest 文件:

If you want to catch (ACTION_ACL_CONNECTED, ACTION_ACL_DISCONNECTED, ACTION_ACL_DISCONNECT_REQUESTED), now you need to add an <intent-filter> to your AndroidManifest file:

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

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

Create filter and register it in onCreate() method:

IntentFilter filter3 = new IntentFilter();
filter3.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter3.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
registerReceiver(mBroadcastReceiver3, filter3);

然后在您的活动/服务中创建广播接收器:

Then create the BroadcastReceiver in your Activity/Service:

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

最后,取消注册:

unregisterReceiver(mBroadcastReceiver3);

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

If you want to read more about state constants, this is from the documentation:

公共静态最终字符串 EXTRA_STATE:

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

Used as an int extra field in ACTION_STATE_CHANGED intents to request the current power state. Possible values are: STATE_OFF, STATE_TURNING_ON, STATE_ON, STATE_TURNING_OFF

公共静态最终字符串 EXTRA_SCAN_MODE:

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

Used as an int extra field in ACTION_SCAN_MODE_CHANGED intents to request the current scan mode. Possible values are: SCAN_MODE_NONE, SCAN_MODE_CONNECTABLE, SCAN_MODE_CONNECTABLE_DISCOVERABLE

这篇关于Android 广播接收器蓝牙事件捕捉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆