我试图通过广播接收器捕获与 android 的配对过程中的事件。看起来,BluetoothDevice.BOND_BONDING
是有效的,但是BluetoothDevice.BOND_BONDED
not.
在旧的 Android 版本中,此功能有效(尝试过 Android 6 和 7),但对于较新的版本(尝试过 Android 9,多种设备),此功能不起作用。为了重现这个问题,我做了一个简单的程序:
Java文件:
package com.example.bluetoothtest;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
BroadcastReceiver receiver;
BluetoothDevice mDevice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)){
mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
//means device paired
Log.d("bt", "bonded");
}
else if(mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d("bt", "bonding");
}
}
}
};
}
@Override
protected void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(receiver, filter);
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(receiver);
}
}
显现:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetoothtest">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
</manifest>
还有其他人注意到这个问题吗?我是否缺少权限?在网上找不到任何相关内容。
您应该尝试检索EXTRA_BOND_STATE
像那样 :
val state = intent.extras?.get(BluetoothDevice.EXTRA_BOND_STATE) as Int
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)