Skip to content Skip to sidebar Skip to footer

Android Bluetooth Enable

I am developing a Bluetooth chat application. The problem is that when i enable Bluetooth the application enables Bluetooth but causes force close. the next time i launch the same

Solution 1:

first:

Declare the Bluetooth permission(s) in your application manifest file. For example:

<manifest... ><uses-permissionandroid:name="android.permission.BLUETOOTH" />
...
</manifest>

Setting up bluetooth:

BluetoothAdaptermBluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}

Enable bluetooth:

if (!mBluetoothAdapter.isEnabled()) {
IntentenableBtIntent=newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

Finding devices:

Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devicesif (pairedDevices.size() >0) {
// Loop through paired devicesfor (BluetoothDevice device : pairedDevices) {
    // Add the name and address to an array adapter to show in a ListView
    mArrayAdapter.add(device.getName() +"\n"+ device.getAddress());
}
}

discovering devices:

// Create a BroadcastReceiver for ACTION_FOUNDprivatefinalBroadcastReceivermReceiver=newBroadcastReceiver() {
@OverridepublicvoidonReceive(Context context, Intent intent) {
    Stringaction= intent.getAction();
    // When discovery finds a deviceif (BluetoothDevice.ACTION_FOUND.equals(action)) {
        // Get the BluetoothDevice object from the IntentBluetoothDevicedevice=     
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        // Add the name and address to an array adapter to show in a ListView
        mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
    }
}
};
// Register the BroadcastReceiverIntentFilterfilter=newIntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

Enabling discovery

IntentdiscoverableIntent=newIntent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);

Post a Comment for "Android Bluetooth Enable"