I am making a Android application that needs to connect with a Bluetooth device. I followed the documentation from android developers but it seems that onReceive() function in the bluetoothReceiver is never getting called. Like no devices are found.
Permissions
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
onCreate() of Main Activity
bluetoothConnect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
enableBluetooth();
}
});
enableBluetooth() - used to start bluetooth
private void enableBluetooth() {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//Bluetooth not supported on device
if(bluetoothAdapter == null){
Toast.makeText(getApplicationContext(), "Device Not Supporting Bluetooth", Toast.LENGTH_SHORT).show();
}
//Bluetooth not enabled
if(!bluetoothAdapter.isEnabled()){
//Open setting to enable bluetooth
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, REQUEST_ENABLE_BT);
}
}
discoverBluetooth() - add to list discovered Bluetooth device and also print to logcat
private void discoverBluetooth() {
bluetoothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d("Device action: ", action);
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String discoveredDeviceName = device.getName() + " " + device.getAddress();
bluetoothList.add(discoveredDeviceName);
Log.d("Device: ", discoveredDeviceName);
}
}
};
}
onActivityResult() - If user starts bluetooth call startDiscovery() and call above function discoverBluetooth()
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_ENABLE_BT){
if(resultCode == RESULT_OK){
Toast.makeText(getApplicationContext(), "Bluetooth Connected" , Toast.LENGTH_SHORT).show();
// Register the BroadcastReceiver
discoverBluetooth();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(bluetoothReceiver, filter); // Don't forget to unregister during onDestroy
boolean isStarted = bluetoothAdapter.startDiscovery();
Toast.makeText(getApplicationContext(), "Bluetooth Discovery status:" + (isStarted? " Started" : " Not Started"), Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Bluetooth Not Connected" , Toast.LENGTH_SHORT).show();
}
}
}
onStop()
@Override
protected void onDestroy() {
unregisterReceiver(bluetoothReceiver);
super.onDestroy();
}