I am trying to discover bluetooth devices and append results to TableLayout.
Basically, I'm trying to start the discovery and print deviceName and rssi to table layout.
Here is my code:
public class DatabaseActivity extends AppCompatActivity {
public BluetoothAdapter bluetoothAdapter;
private final BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress();
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
// Append to tableBLE
TableLayout tl = findViewById(R.id.tableBLE);
appendTableFront(tl, deviceName + "_" + rssi);
Log.d("PBK_Test - Detected", deviceName + "_" + rssi);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
// Bluetooth
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
}
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 0);
}
// Start Discovery
bluetoothAdapter.startDiscovery();
// Register for broadcasts when a device is discovered.
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
// Make discoverable
if (bluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
public void appendTableFront(TableLayout tl, String msg) {
TableRow newRow = new TableRow(this);
newRow.setBackgroundColor(Color.GRAY);
newRow.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
TextView label_id = new TextView(this);
label_id.setText(msg);
label_id.setTextColor(Color.WHITE);
label_id.setPadding(5, 5, 5, 5);
newRow.addView(label_id);
tl.addView(newRow);
}
}
I can become discoverable, but not detecting other devices.
I tried the built-in bluetooth discovery and it works fine.
Edit:
I added Log.d("PBK_Test - Detected", deviceName + "_" + rssi);
to onReceive
and it is not shown as well.
I figured it out myself.
The problem is not in the code --
You have to get into Settings -> App -> <app_name> -> Permissions, to manually give your app permissions, EVEN IF YOU HAVE DECLARED THEM IN MANIFEST.
Citation: This video https://www.youtube.com/watch?v=dLZDJgblgj8