views:

47

answers:

1

I want to send a broadcast from a new thread is start.

This is what i tried :

        new Thread(new Runnable() {
        public void run() {
            //some other code for timing.
            // ..
            // ..
            Intent broadcastIntent = new Intent();
            broadcastIntent.setAction(Intent.ACTION_ANSWER);
            this.sendBroadcast(broadcastIntent);
        }
    }).start();

But ofcourse i need context..this won't work. How can i handle this.

A: 

What I usually do, although is quite hacky, is the following:

final Context mCtx = this;
new Thread(new Runnable() {
    public void run() {
        //some other code for timing.
        // ..
        // ..
        Intent broadcastIntent = new Intent(mCtx, TargetClass.java);
        broadcastIntent.setAction(Intent.ACTION_ANSWER);
        this.sendBroadcast(broadcastIntent);
    }
}).start();

Also, remember to include the target Java class in the Intent constructor.

Hope it helps!

José Manuel Díez
Maybe this will make sense if Thread object is and instance of inner type of some Context's subclass? And there's no Thread.sendBroadcast method. Correct call is SomeActivityName.this.sendBroadcast(broadcastIntent).
Aleksander O
sorry, I meant mCtx.sendBroadcast(broadcastIntent).
José Manuel Díez