Pair a bluetooth device in Android Studio

后端 未结 1 1338
囚心锁ツ
囚心锁ツ 2021-01-21 12:28

I\'m creating an app that should connect via bluetooth to a specific device.

I want my app to connect with this device no matter it is already paired or not.

For

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-21 13:18

    First request BLUETOOTH_ADMIN permission.

    Then make your device discoverable:

    private void makeDiscoverable() {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
            Log.i("Log", "Discoverable ");
        }
    

    Then create a BroadcastReceiver to listen to action from system:

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Message msg = Message.obtain();
                String action = intent.getAction();
                if(BluetoothDevice.ACTION_FOUND.equals(action)){
                   //Found, add to a device list
                }           
            }
        };
    

    And start searching for devices by registering this BoardcastReceiver:

     private void startSearching() {
            Log.i("Log", "in the start searching method");
            IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            BluetoothDemo.this.registerReceiver(myReceiver, intentFilter);
            bluetoothAdapter.startDiscovery();
        }
    

    After devices come from the BroadcastReceiver into a list, select your device from the list and createBond() with this:

     public boolean createBond(BluetoothDevice btDevice)  
        throws Exception  
        { 
            Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
            Method createBondMethod = class1.getMethod("createBond");  
            Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);  
            return returnValue.booleanValue();  
        } 
    

    Then use your code above to manage with bonded devices.

    0 讨论(0)
提交回复
热议问题