Can I send an event from a thread to an action?

If I want to send an event, for example. OnClick, to activity from a stream? Thank.

Expected workflow 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.
       }
   }
+3
source share
4 answers

You will need to use Handlers to update the interface.

+1
source

You can always send a message from a thread to an action, for example:

//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 a message that will contain some values.

+4
source

, OnSomeEvent() HelloAndroid ThreadA, ?

If so, you can fix:

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

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

0
source

Source: https://habr.com/ru/post/1730304/


All Articles