2

My app have a background service that detect objects via bluetooth, and I want to show a dialog in the current activity (Logic to detect app in foreground or background is done) when a BT object is detected. I read about BroadcastReceiver class, but I don't know how can send data from my service to a broadcast for my current activity to show a Dialog in the Activity.

If you know another solution that will be ok

4 Answers4

1

You can use this Android service broadcastreceiver example to achieve your goal.

As alternatives you need to provide your Service class a callback to the MainActivity. You can use Bound services as a starting point.

Radu Ionescu
  • 3,462
  • 5
  • 24
  • 43
0

As far as I understand, you would not send data from the service to your class. You would start the class in your current activity with a listener waiting for response from your service. If a positive response is given the dialog is shown

BroadcastReceiver class is used within the service and not within your current activity class.

Parsa
  • 3,054
  • 3
  • 19
  • 35
0

when your service detects device,you should send a broadcast receiver from the service,like this:

 final Intent intent = new Intent(action);
 sendBroadcast(intent);

And in your activity register this receiver with the action.

you can refer this,it's a BLE sample by google:

starkshang
  • 8,228
  • 6
  • 41
  • 52
0

The best thing you can do to receive such broadcasts is to look for the Bluetooth State Changed, as is documented here. Your code will look something like this (Copied from this question, with some modification)

public class BluetoothReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            //See if new bluetooth objects detected
        }
    }
};

Next you need to add your receiver to your manifest. Something like this is needed:

<receiver android:name=".BlutoothReceiver" >
    <intent-filter>
        <action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
    </intent-filter>
</receiver>" />
</receiver>

Beyond this, read the documentation listed above.

Community
  • 1
  • 1
PearsonArtPhoto
  • 38,970
  • 17
  • 111
  • 142