Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How to use a local broadcast receiver?

I'm trying to use a local broadcast receiver.

In order to do so I"ve done the next steps -

1) At an Activity, where Iwould like something to happen, I've created a class -

private class NewGroupReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("The group ", "GOT IN THE RECIVING");
        Toast.makeText(this, "Working",Toast.LENGTH_SHORT).show();  
    }

}

2) At the same activity I've used the next code in order to create a receiver -

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    NewGroupReceiver receiver = new NewGroupReceiver();

    //the intent filter will be action = "com.example.demo_service.action.SERVICE_FINISHED"
    IntentFilter filter= new IntentFilter("com.example.apps.action.NEW_GROUP");

    // register the receiver:
    registerReceiver(receiver, filter);
}

3) At the a service class I've used the next code to know when something has happened-

Intent resultsIntent=new Intent("com.example.apps.action.NEW_GROUP");

LocalBroadcastManager localBroadcastManager =LocalBroadcastManager.getInstance(this);

localBroadcastManager.sendBroadcast(resultsIntent);

Now the problem is that when the thing I WOuld like to know has happen - I see the it's get into the code that I've used at step 3, but it doesen't seem to get into the BroadcastReceiver - the step 1 code.

Any idea what am I doing wrong here? Thanks for any kind of help.

like image 709
4this Avatar asked Apr 28 '14 17:04

4this


People also ask

How can I use local broadcast receiver in Android?

For performing a specific action using Broadcast manager we have to firstly register our Broadcast and then only we can use this broadcast to receive updates. There are 2 ways to register our broadcast we can register it in our Android Manifest file or in our Activity where we want to receive its updates.

What is local broadcast manager in Android?

LocalBroadcastManager is an application-wide event bus and embraces layer violations in your app: any component may listen events from any other.

When should I use LocalBroadcastManager?

If you want some kind of broadcasting in your application then you should use the concept of LocalBroadcastManager and we should avoid using the Global Broadcast because for using Global Broadcast you have to ensure that there are no security holes that can leak your data to other applications.


1 Answers

You are using the LocalBroadcastManager to send the request, but you register the receiver on the "global" Intent. You should either use LocalBroadcastManager to register the receiver or send the broadcast on the application context:

Step 2

LocalBroadcastManager.getInstance(this).registerReceiver (receiver, filter);
like image 189
JohnnyAW Avatar answered Nov 10 '22 08:11

JohnnyAW