蓝牙未与其他设备自动配对

时间:2020-05-21 14:15:04

标签: java android bluetooth

我有一个应用程序,想在蓝牙打开后立即与最近的设备自动配对。下面是我的代码

 BluetoothAdapter BA; 
  BLE_PIN ="1234";
  private final BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {
@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);
        device.createBond();

    }else if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)){
        BluetoothDevice bluetoothDevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        bluetoothDevice.setPin(BLE_PIN.getBytes());
        Log.e(TAG, "Auto-entering pin:"+BLE_PIN);
        Toast.makeText(getApplicationContext(),"Pin entered"+BLE_PIN,Toast.LENGTH_SHORT).show();
        bluetoothDevice.createBond();
        Toast.makeText(getApplicationContext(),"Pin entered request sent",Toast.LENGTH_SHORT).show();

        Log.e(TAG,"pin entered and request sent...");}
  };
 @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);


setContentView(R.layout.activity_main);
BA=BluetoothAdapter.getDefaultAdapter()
if (BA.isEnabled()){
    startService(new Intent(getBaseContext(), MyService.class));
    IntentFilter filter=new IntentFilter(BluetoothDevice.ACTION_FOUND);

    filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
getApplicationContext().registerReceiver(broadcastReceiver,filter);
    BA.startDiscovery();
    a.setText("turn off bluetooth");
    Intent getvis=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    getvis.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,0);
    startActivity(getvis);

我仍然没有收到与我的PC配对的请求enter image description here

请帮助

0 个答案:

没有答案