WebRookie February 2016

Can a service receive its own broadcasts?

If I had a service called MyService and it looked like this, will the service's BroadcastReceiver recieve its own broadcast from the "sendData" method ??

What I am basically asking is is there going to be a problem if I used the same IntentFilter Constants.SERVICE of the broadcast receiver as an Intent Action to send broadcasts to my activity ?

MyService.java

public class PlayerService extends Service {
    private FFmpegMediaPlayer mp;
    private BroadcastReceiver receiver;

    @Override
    public void onCreate() {
        super.onCreate();
        ...
        registerReceiver(receiver, new IntentFilter(Constants.SERVICE));
        ...
    }
    ...
    public void sendData() {
        Intent intent = new Intent(Constants.SERVICE);
        sendBroadcast(intent);
    }
}

Answers


WebRookie February 2016

As Adil Soomro and rupesh jain mentioned it apparently won't be a problem as the service cannot receive it's own broadcasts.

EDIT

Actually after experimenting with it I found that the service can receive its own broadcasts if the BroadcastReceiver had the same IntentFilter as the broadcast intent.


Doug Stevenson February 2016

You could certainly try this, but it seems completely unnecessary. Bear in mind that what you're proposing is not for a service to receive its own broadcast (services don't receive any broadcasts), but you're define a broadcast receive inside the service and that is what receives the broadcast.

If you are trying to communicate between components, it's probably better to use LocalBroadcastManager, or some kind of event bus, because your broadcasts are going to all apps that could be listening, not just this one app.

Post Status

Asked in February 2016
Viewed 3,779 times
Voted 14
Answered 2 times

Search




Leave an answer