tags:

views:

84

answers:

4

If I want to send an event, e.g. OnClick, to an activity from a thread? Thanks.

The expected work flow is below:

public class HelloAndroid extends Activity {

   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       Crate threadA
       Start threadA
   }

   public void OnSomeEvent() {
       do something that changes the views in this activity;
   }

   private class ThreadA extends Thread {
       public void run() {
           do something ...

           Send Some Event to Activity HelloAndroid.
       }
   }
A: 

If I understand correctly, you want to call the method OnSomeEvent() of HelloAndroid from your inner ThreadA class, right?

If this is the case you could right:

private class ThreadA extends Thread {
    public void run() {
        HelloAndroid.this.OnSomeEvent();
    }
}

or even simpler, just call OnSomeEvent() method directly.

Alex
OnSomeEvent() will have code that change the UI components, while it is not allowed to change UI component in the other thread than the UI thread. So, you suggestion will not work.
+1  A: 

All UI related event have to executed from UI Thread. http://developer.android.com/guide/appendix/faq/commontasks.html#threading

Alex Volovoy
I know. If the thread sends an event to activity, and a method will be triggered in the activity, then this method will be executed in UI thread.
+1  A: 

You will have to use Handlers to update UI.

Tushar
Yes, I realized that Handlers can do what I need. Thanks.
+3  A: 

You can always send a message from a thread to the activity, like that:

//this should be in your Activity class
private Handler SomeHandler = new Handler() {
    public void handleMessage(Message msg) {
        ReactOnMessage();
    }
};


private class SomeThread implements Runnable {
    public void run() {
        doSomething();
        SomeHandler.sendEmptyMessage(0);
    }
}

You can also create message, which will contain some values.

Michal Dymel