0

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?

Sara Fuerst
  • 5,688
  • 8
  • 43
  • 86
  • You should check this [post](https://stackoverflow.com/questions/2463175/how-to-have-android-service-communicate-with-activity) with many options of how to achieve communication between service and activity – Gustavo Pagani Mar 29 '18 at 14:30
  • @Gustavo based on what I'm seeing from that post, should I have moved my `BroadcastReceiver` to my Service? Or should it have stayed in the Activity? – Sara Fuerst Mar 29 '18 at 14:41
  • You can achieve this in several way . First Make Service as Bounded . Second Set a callback to Service . Third you can use Local Broadcast or `EventBus` to notify Activity . If Service only serves the Activity the go with first option make it Bounded . – ADM Mar 29 '18 at 14:45

0 Answers0