Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Messaging to UI thread

I am developing a serialport application for knx modules in android. I can send and recieve commends to knx modulde. I want to change ui(for ex. button properties) when a message recieved from serialport. I tried it with handlers but i havent be able to change ui. help me plss.

@Override public void OnSerialsData(final byte[] buffer, final int size) { .... }

its my serialport listener function calling insine ReadThread. This thread is starting in differend package from my activity. I want to send a message in this method to main activity.

like image 533
Fatih POLAT Avatar asked Sep 03 '25 10:09

Fatih POLAT


2 Answers

You can use Activity.runOnUiThread() to communicate with UI thread. Read more about Processes and Threads, especially about worker threads.

For example within your OnSerialsData, you can call

mActivity.runOnUiThread(new Runnable() {
    public void run() {
        mActivity.mButton.setText("message arrived!");
    }
}
like image 52
auselen Avatar answered Sep 04 '25 22:09

auselen


first you have to create a static handler inside your main activity:

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

public static Handler myHandler = new Handler(){

    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        super.handleMessage(msg);

        Log.e("Test", msg.getData().getCharSequence("MAINLIST").toString());

    }

};
}

then in your socket class:

public void OnSerialsData(final byte[] buffer, final int size) {

    Message msg = MainActivity.myHandler.obtainMessage();
    Bundle bundle = new Bundle();
    bundle.putCharSequence("MAINLIST", "IS_OK");
    msg.setData(bundle);
    MainActivity.myHandler.sendMessage(msg);

}

but you have to ensure that your handler must be created before you call OnSerialsData method.

I hope this help.

like image 25
detay34 Avatar answered Sep 04 '25 22:09

detay34