问题描述
大家好,我要添加一个广播接收器,以便在自动设置了引脚之后找到具有给定名称的蓝牙设备。 但是广播接收器无法正常工作(可能是onReceive未触发)。请帮助我找出我的错误
我添加了以下权限:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
这是活动:
public class ActivityBtConnection extends AppCompatActivity {
public static Context context;
BroadcastReceiver mReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xaxss);
context = this;
mReceiver = new BroadcastReceiver() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onReceive(Context context,Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String name = device.getName();
if (name != null && name.contains("HC-06")) {
device.createBond();
}
} else if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String name = device.getName();
if (name.contains("HC-06")) {
try {
byte[] pin = (byte[]) BluetoothDevice.class.getMethod("convertPinToBytes",String.class).invoke(BluetoothDevice.class,"1234");
Method m = device.getClass().getMethod("setPin",byte[].class);
m.invoke(device,pin);
device.getClass().getMethod("setPairingConfirmation",boolean.class).invoke(device,true);
device.getClass().getMethod("cancelPairingUserInput",boolean.class).invoke(device);
} catch (Exception e) {
e.printStackTrace();
}
Intent i = new Intent(context,ActivityMoney2Device.class);
context.startActivity(i);
}
}
}
};
}
@Override
protected void onResume() {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
filter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver,filter);
super.onResume();
}
@Override
protected void onPause() {
unregisterReceiver(mReceiver);
super.onPause();
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)