Search code examples
androidobserver-patternbroadcastandroid-2.1-eclair

Can I send a broadcast from a class which does not extend activity?


I have a class which implements an Observer.

I have a method which is triggered in this class when the Obervered state changes, I want to sent out a broadcast in this method. This means my activity can listen for those broadcast messages and do something with the data.

This is what I have so far

public class DoStuff extends BroadcastReceiver implements Observer
{
    public void observe(String message)
    {
        Log.d("TEST", "Inside observe() on DoStuff " + message);

        // Here I want to send out a broadcast to MyActivity with message
        // in the extras
    }

}

I can't use context.sendBroadcast, because I don't have access to the application context here, how can I achieve this?

Thanks in advance


Solution

  • Why do you use BroadcastReciever to implement Observer interface? I guess a Service or an Application are better candidates in case you really need access to a Context instance. BroadcastRecievers are only alive during onRecieve() method call, so from my perspective it makes no sense to implement Observer interface using them.