简体   繁体   中英

Updating the UI by receiving message from handler

I would like to receive the message from my handler (from a service) and set the text to my editext in my UI. I am sending the message from background thread to main thread using handler inside the service. I created one handler in background thread and one in the main thread (in the constructor). Now I would like to send this message to my MainActivity and update UI. I have the following code.

MyService.java

public class myLocalThread extends Thread {

@SuppressLint("HandlerLeak")
myLocalThread() throws IOException {

mhandler = new Handler() {
  @Override
  public void handleMessage(Message msg) {
    switch (msg.what) {
      case MSG:

        DeviceMessageStatus statusObject = (DeviceMessageStatus) msg.obj;
        statusClass = statusObject.getClass();
        try {
            statusField = statusClass.getField("screening_information");
            statusFieldValue = statusField.get(statusObject);
        Log.i("TAG", "Message OBJECT :" + statusFieldValue);
    }

  };
 }
}

I got the message forwarded from my background thread to mainthread but inside the service. How can I Update UI in the MainActivity . Should I create a another handler ? Here is what I did

MainActivity.java
Object statusFieldValue;
onCreate(Bundle savedInstanceState){
    number = (EditText) findViewById(R.id.dialpad);
    number.setText((Integer) statusFieldValue);
    Log.i("RL_RX", "onCreate: " + statusFieldValue);
}

This throws an nullPointerError the acitivity couldnot start. How can I retreive the message in the messagequeue of UI thread. What am I missing here ?

您声明了一个命名为“ mhandler”的处理程序,但是在mhandler中,您仍然使用mhandler发送消息,这是一个无限循环吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM