Search code examples
androidbroadcastreceiverandroid-service

Broadcast reciever not working from service


I am trying to use BroadcastReceiver inside my service but it is not working properly.

I am starting my service in an onCreate in my activity. Then in the services onCreate I am calling the following to register the Broadcast reciever:

    IntentFilter filter = new IntentFilter();
    registerReceiver(DataUpdateReceiver, filter);

Here's the broadcast receiver i am trying to register:

    private BroadcastReceiver DataUpdateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        Toast.makeText(context, "Test", Toast.LENGTH_LONG).show();

    }
};

Then else where in the Activity I am trying to call this so therefor the Toast message will be displayed.

            Intent i = new Intent();
            sendBroadcast(i);

But the Toast is not being displayed, I have also tried logging but nothing shows up. If anyone could help me out on this it would be appreciated, ty.


Solution

  • In my opinion, you have to specify action (or actions), which fire onReceive() method. Something like this might help you:

    IntentFilter filter = new IntentFilter("some_action");
    registerReceiver(DataUpdateReceiver, filter);
    
    ...
    
    Intent i = new Intent("some_action");
    sendBroadcast(i);