Jack
Jack

Reputation: 2053

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.

Upvotes: 0

Views: 879

Answers (2)

J.Vassallo
J.Vassallo

Reputation: 2292

Declare on top of the class

public final static String MY_RECEIVER_START = "com.yourcompanyname.appname.MY_RECEIVER_START";

private Radio radio;

In the service constructor

    //Initiate our receiver
    radio = new Radio();

    //Activate our recevier
    context.registerReceiver(radio, new IntentFilter(MY_RECEIVER_START));

Also in the service, create the receiver class and the method which shows toast

/**
 * Receiver Class
 * This setup checks for the incoming intent action to be able to
 * attach more messages to one receiver.
 */
private class Radio extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(MY_RECEIVER_START)){
            //show toast


        }

    }
}

After from anywhere in the application send message to our radio

context.sendBroadcast(new Intent("com.yourcompanyname.appname.MY_RECEIVER_START"));

Upvotes: 1

skywall
skywall

Reputation: 4005

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);

Upvotes: 1

Related Questions