I am new to Android development, and have followed a tutorial to set up a Bluetooth activity for my mobile application. I got the code from the tutorial working, but then needed to move my Bluetooth code over to a Service. In the process of moving the code over, I am having trouble handling when the code updates an ArrayAdapter.
//BluetoothService.java
public void discover(View view){
//Check if the device is already discovering
if(bluetoothAdapter.isDiscovering()){
bluetoothAdapter.cancelDiscovery();
Toast.makeText(getApplicationContext(), "Discovery stopped", Toast.LENGTH_SHORT).show();
} else {
if(bluetoothAdapter.isEnabled()){
bluetoothAdapter.startDiscovery();
Toast.makeText(getApplicationContext(), "Discovery started", Toast.LENGTH_SHORT).show();
registerReceiver(broadcastReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
} else {
Toast.makeText(getApplicationContext(), "Bluetooth is not on", Toast.LENGTH_SHORT).show();
}
}
}
final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name to the list
String deviceName = device.getName();
bluetoothArrayAdapter.add(device.getName() + "\n" + device.getAddress());
bluetoothArrayAdapter.notifyDataSetChanged();
}
}
};
In the BroadcastReceiver
, bluetoothArrayAdapter
is not defined, as it is defined in the activity. The activity simply calls the discover
function:
//BluetoothActivity.java
private void discover(View view){
bluetoothArrayAdapter.clear(); //Clear items
bluetoothService.discover(view);
}
Being new to Android and Java, I'm not how I should go about updating the ArrayAdapter. Should I be creating an array to return to the activity, which is then used to update the bluetoothArrayAdapter
?