Kirchhoff1415
Kirchhoff1415

Reputation: 41

Pair a bluetooth device in Android Studio

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 now I have this

private void findDevice() {
    Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
    if (pairedDevices.size() > 0) {
        for (BluetoothDevice device : pairedDevices) {
            if (device.getName().equals(DEVICE_NAME)) {
                bluetoothDevice = device;
                deviceFound = true;
                break;
            }
        }
    }
}

But this function connects only to paired devices. If my device isn't already paired, I want to pair it. Have no idea how to do this.

Can someone get me any advice please?

Upvotes: 2

Views: 25703

Answers (1)

nhoxbypass
nhoxbypass

Reputation: 10152

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.

Upvotes: 5

Related Questions