i've got problem on implementing this functionality in Android... i need only to output the decibel redorded from the microphone, and it's a thing that i can't understand:
public class Noise extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
MediaRecorder recorder=new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
Timer timer=new Timer();
timer.scheduleAtFixedRate(new RecorderTask(recorder), 0, 500);
}
private class RecorderTask extends TimerTask{
TextView risultato=(TextView) findViewById(R.id.risultato_recorder);
private MediaRecorder recorder;
public RecorderTask(MediaRecorder recorder){
this.recorder = recorder;
}
public void run(){
risultato.setText(""+recorder.getMaxAmplitude());
}
}
}
In the textview, the result is printed the first time only, and it's 0, and then the app crash with: 11-29 14:43:27.133: E/AndroidRuntime(25785): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
I've searched around, but i can't find a comprehensive example... only examples with a lot of things and class that i don't need. can i fix this problem?
UI components can only be modified from the UI thread.
Your task is running in a background thread, so you need to force the TextView
update to be done in the UI thread. You can achieve it with the Activity.runOnUiThread
method.
Try this:
public void run(){
runOnUiThread(new Runnable() {
@Override
public void run() {
risultato.setText("" + recorder.getMaxAmplitude());
}
});
}
instead of
public void run(){
risultato.setText(""+recorder.getMaxAmplitude());
}