0

I'm trying to use broadcasters to send messages from a child thread to the main UI thread. So i have a broadcast receiver on my activities (i hate multiple) and i want to be able to send them messages from one single child thread (runnable).

Here is what i'm doing in the child thread:

Intent broadcastIntent = new Intent();
broadcastIntent.setAction(ResponseReceiver.ACTION_RESP);
broadcastIntent.putExtra("Controller", "connect");
context.sendBroadcast(broadcastIntent);

But the problem is how i define context? It gives the exception "context cannot be resolved" If i don't use it, it won't find "sendBroadcast" method. So how can this be done?

AndreiBogdan
  • 10,858
  • 13
  • 58
  • 106

1 Answers1

5

You can pass in your Activity or Application context to your thread.

If you're in an Activity, you can do:

    Context myContext;
    myContext = this;

or

    myContext = getApplicationContext();

Then pass in context to your child thread:

    new Thread(new SomeThread(myContext)).start();



    public class SomeThread implements Runnable
    {
        Context context;
        public SomeThread(Context ctx)
        {
            context = ctx;
        }

        public void run()
        {
            // Do stuff with context.
        }
    }
triad
  • 20,407
  • 13
  • 45
  • 50
  • Yeah, that's right. the problem is i wanted to avoid that :) Initially i was using Handlers to send messages to the activities, and i had to send the Handler reference to the child thread every time the activity changed. This is not really different than that :( Crap. – AndreiBogdan Feb 22 '12 at 18:14
  • Ah, if you just want to access the context from anywhere you can try some of the ideas in this thread: http://stackoverflow.com/questions/987072/using-application-context-everywhere – triad Feb 22 '12 at 18:27