2

I am building a simple chat application. When I receive a message, I sent a broadcast message.

As this is run inside a thread started by a service, I pass the context to the thread. MyConnection is a class extending thread.

@Override
public void onCreate() {
    super.onCreate();       
    connection = new MyConnection(getApplicationContext());
}

So inside the thread when I receive a message, I do this...

Intent i = new Intent();
i.putExtra("from", message.getFrom());
i.putExtra("message", message.getBody());
i.setAction(MyService.MESSAGE_RECEIVED);                
_context.sendBroadcast(i);

_context is the getApplicationContext() I passed to the constructor of the thread. I have the receiver registered in my Manifest file.

So this is all working and my receiver receives the message successfully.

Now I want to change this to use the LocalBroadcastManager. So what I did was simply change the _context.sendBroadcast(i) to

LocalBroadcastManager.getInstance(_context).sendBroadcast(i);

However my BroadcastReceiver is not receiving any of the broadcasts sent this way.

What am I doing wrong? Do I need to register the receiver in a different way in Manifest to receive local broadcasts? Are there any other steps required to make it work?

Ranhiru Jude Cooray
  • 19,542
  • 20
  • 83
  • 128

1 Answers1

1

Did you register your broadcast receiver with registerReceiver or in manifest?

Instead of passing getApplicationContext() pass this, because Service extends Context, too.

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158
  • So it doesn't matter which context I pass? I thought I have to use the same context for both sending and receiving. That is why I used the `getApplicationContext`. – Ranhiru Jude Cooray Jun 07 '13 at 05:53
  • No, it doesn't matter as long as you pass the same intent for broadcast. Indeed, one application can send a broadcast and another one receive it, contexts are then obviously different. – Alexander Kulyakhtin Jun 07 '13 at 06:00