Within one Activity I have th following piece of code:
public void onStartMonitoringToggleClicked(View v) {
// Perform action on clicks
if (((ToggleButton) v).isChecked()) {
monitoringCanRun = true;
new Thread(new Runnable() {
public void run() {
performMonitoring(); //start the monitor
}
}).start();
} else {
monitoringCanRun = false;
}
}
public void performMonitoring() {
while (monitoringCanRun) {
float parametervalue = Monitor.getParameterValue();
//need to send the parameter value to the parameter screen's handler now
Message msg = mHandler
.obtainMessage(MESSAGE_UPDATE_PARAMETER_VALUE);
Bundle bundle = new Bundle();
bundle.putFloat(PARAMETER_VALUE, parametervalue);
msg.setData(bundle);
mHandler.sendMessage(msg);
Log.i("x", "sending MSG------>"); //this gets called EVERY 4 seconds
try { //we delay to make debugging easier
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public final int MESSAGE_UPDATE_PARAMETER_VALUE = 1;
public final String PARAMETER_VALUE = "paramVal";
//the handler that receives the parameter values from the monitoring thread
public final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.i("x", "<-------RECEIVED MSG"); //this gets called only ONCE???????
switch (msg.what) {
case MESSAGE_UPDATE_PARAMETER_VALUE: {
float parameter_value = msg.getData().getFloat(PARAMETER_VALUE);
if (DEBUG)
Log.i(this.getClass().getSimpleName(),
"-> "
+ Thread.currentThread().getStackTrace()[2]
.getMethodName()
+ " parameterValue="
+ String.format("%4.2", parameter_value));
}
break;
}
}
};
I have used handlers quite alot, but never had this kind of problem. Is there anything basic wrong here?
Many thanks
Have you tried not using the thread? Could you try to use the handler where it calls its self every 4 seconds? I have modified a project where I use Handler’s to do call backs. Yes I would be on the UI thread but it doesn’t look like you are doing any blocking IO. I may be mistaken.
Also, why not just save the data into a global share and access it across threads. I think the way you are doing it you should have access to the threads data. Again this is just an idea. I hope this helps!