Android BLE-BroadcastReceiver没有收到BLE连接更新(ACTION_STATE_CHANGED等)

时间:2018-10-04 03:08:49

标签: android bluetooth broadcastreceiver bluetooth-lowenergy android-broadcastreceiver

我的onCreate()看起来像这样:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    IntentFilter myIntentFilter = new IntentFilter("BATTERY_LEVEL");
    myIntentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    myIntentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
    LocalBroadcastManager.getInstance(this).registerReceiver(onBroadcastReceive, myIntentFilter);

More things....
}

然后我在主要活动下面有这个课:

BroadcastReceiver onBroadcastReceive = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("Main Activity", "Broadcast received");
        String action = intent.getAction();
        Log.i("Action is", action);
        if (action != null) {
            switch (action) {
                case "BATTERY_LEVEL":
                    I can take it from here...
            }
        }

我可以从那里拿走。我正在查看“动作是”打印输出,以查看广播的到来。

稍后,在我的主应用程序中,我调用了一项服务,该服务在前台启动了蓝牙连接。我知道连接很好。首先,该服务中的此代码正确运行,并且我得到“ gattCallback STATE_CONNECTED”:

private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            //status of 0 if operation succeeds
            Log.i("onConnectionStateChange", "Status: " + status);
            switch (newState) {
                case BluetoothProfile.STATE_CONNECTED:
                    Log.i("gattCallback", "STATE_CONNECTED");
                    android.os.SystemClock.sleep(600);
                    gatt.discoverServices();
                    break;
                case BluetoothProfile.STATE_DISCONNECTED:
                    Log.e("gattCallback", "STATE_DISCONNECTED");
                    mGatt.close();
                    break;
                default:
                    Log.e("gattCallback", "STATE_OTHER");
            }

        }
    }

第二,该服务将Intents发送回主应用程序(onCreate()中定义的“ BATTERY_LEVEL”操作”。这些电池电量来自蓝牙设备。我得到的消息是

I/Main Activity: Broadcast received
I/Action is: BATTERY_LEVEL

但是,即使我故意打开和关闭蓝牙,也无法获得ACTION_STATE_CHANGED或ACTION_CONNECTION_STATE_CHANGED。是因为它发生在其他服务中吗?有办法解决这个问题吗?

0 个答案:

没有答案