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.
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!");
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With