Search code examples
androidaccessibility

What is the proper way to send a broadcast from an activity to a service?


I have an activity with a button than sends a broadcast to an accessibility service (they're in the same app but different processes). I'm sorry if this was already answered many times but I can't find the proper method to do it. To be clear what I wrote works but I don't know if it's the proper way. I wrote this in the activity:

Intent intent = new Intent("roastie_toastie");
sendBroadcast(intent);

And in the accessibility service wrote this:

IntentFilter intentFilter = new IntentFilter("roastie_toastie");
receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        
    }
};
registerReceiver(receiver, intentFilter);

Does anything else need to be added to the intent and intentFilter to be sure that this broadcast does not consume any battery and is only sent and received inside the app?


Solution

  • is there any way to also specify the sender's packageName for the receiver's IntentFilter so that it only listens to broadcasts from inside the app?

    No, sorry. However, if this is all one app, then you do not need to use registerReceiver().

    Presumably, right now, in your manifest, you have a <service> element that has android:process to have the service run in a separate process from the rest of the app. You can have a <receiver> element that has the same android:process attribute, to have it run in the same process as the service. If you have the <receiver> also be android:exported="false", then only your app can send broadcasts to it. Your sending code would use an explicit Intent, identifying the specific BroadcastReceiver class.

    Once you have your broadcast over to the service's process via that BroadcastReceiver, it and the service can communicate via some common process-wide singleton.