Hi I’m having some problems to show a toast message, actually the program crash saying that I’m trying to disply a toast in the wrong thread or something like that.
I have been reading some other questions about the topic and I think the soultions is something like using a handler to comunicate with the UI, but not sure how to do it, could any one share with me an example/tutorial about how to launch a toast mesage from any part of the code?
For example I’m trying something like this: [the problematic line is between** **]
public class SamplesTiming extends Activity {
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_samples_timing);
...
}
private void setButtonHandlers() {
((Button)findViewById(R.id.btnStart)).setOnClickListener(btnClick);
((Button)findViewById(R.id.btnStop)).setOnClickListener(btnClick);
}
private void enableButton(int id,boolean isEnable){
((Button)findViewById(id)).setEnabled(isEnable);
}
private void enableButtons(boolean isRecording) {
enableButton(R.id.btnStart,!isRecording);
enableButton(R.id.btnStop,isRecording);
}
private void startRecording(){
...
recordingThread = new Thread(new Runnable() {
//@Override
public void run() {
writeAudioDataToFile();
}
},"AudioRecorder Thread");
recordingThread.start();
}
private void writeAudioDataToFile(){
...
while(isRecording){
...
read = recorder.read(data, 0, bufferSize);
if(condition) **Toast.makeText(getApplicationContext(),
"it happen", Toast.LENGTH_LONG).show();**
...
}
}
private void stopRecording(){
if(null != recorder){
isRecording = false;
recorder.stop();
recorder.release();
recorder = null;
recordingThread = null;
}
}
private View.OnClickListener btnClick = new View.OnClickListener() {
// @Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnStart:{
enableButtons(true);
startRecording();
break;
}
case R.id.btnStop:{
enableButtons(false);
stopRecording();
break;
}
}
}
};
}
Thank you very much for your time
use Activity.runOnUiThread for showing Toast from background thread as :