3

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.

ccellar
  • 10,326
  • 2
  • 38
  • 56
Fatih POLAT
  • 147
  • 1
  • 4
  • 16

3 Answers3

6

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!");
    }
}
auselen
  • 27,577
  • 7
  • 73
  • 114
3

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.

detay34
  • 44
  • 6
1

just extending @auselen answer.

Create on your activity the following:

public void messageReceived(final String msg){
runOnUiThread(new Runnable() {

    @Override
    public void run() {
    // Put here your code to update the UI

    }
});
} 

and then you can call this from any class that have a reference to your activity. If the class does not have a reference to the activity, then you should pass the reference to it.

Budius
  • 39,391
  • 16
  • 102
  • 144