Search code examples
androidbroadcastreceiverandroid-broadcastlocalbroadcastmanager

LocalBroadcastReceiver doesn't work from inside a thread


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?


Solution

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

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