Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to send an event from a thread to an activity?

Tags:

java

android

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.
       }
   }
like image 569
user256239 Avatar asked Feb 27 '23 17:02

user256239


1 Answers

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.

like image 103
Michal Dymel Avatar answered Mar 24 '23 22:03

Michal Dymel