Yanshof Yanshof - 4 months ago 8
Android Question

fail to control when a beep will appear ( code attached )

I trying to write simple application that will make a beep each X milliseconds.
There are 2 button that will increase and decrease the X ( up will do ++X and down will do --X )

When i trying to set the time of the repeat of the sound i fail to set the X time.

When i start the 'schedule' for 5 seconds ( 5000 milliseconds ) i always get the beep each 1 second - and i can't set the time of the interval at all.

Why i keep failing on the interval set time ?????????????

The code:

private long _valueToDisplay = 5000;
private Timer _timeTimeToBeep;
private TimerTask _task;
private Thread _thread;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_timeTimeToBeep = new Timer();

_task = new TimerTask() {

@Override
public void run() {

_thread = new Thread(new Runnable() {
@Override
public void run() {
playSound();
}
});

_thread.start();
}
};
}


public void playSound(){
final ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);
toneGenerator.startTone(ToneGenerator.TONE_PROP_BEEP);
}


public void startPlayClickBtn(View view) throws InterruptedException {
//_timeTimeToBeep.schedule(_task, 3000, 3000);
_timeTimeToBeep.schedule(_task, 0, _valueToDisplay);
}

Answer

Change your code like this :

private long _valueToDisplay = 1000;
private Timer _timeTimeToBeep;
private TimerTask _task;
private Thread _thread;
final ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_eep);
    _timeTimeToBeep = new Timer();

    _task = new TimerTask() {

        @Override
        public void run() {

            _thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    playSound();
                }
            });

            _thread.start();
        }
    };
}


public void playSound(){

    toneGenerator.startTone(ToneGenerator.TONE_PROP_BEEP);
}


public void startPlayClickBtn(View view) throws InterruptedException {
    //_timeTimeToBeep.schedule(_task, 3000, 3000);
    _timeTimeToBeep.schedule(_task, 0, _valueToDisplay);
}

All i have done is create a single constant ToneGenerator object. In your code every 5 seconds you were creating a new object of ToneGenerator. Thats why you were getting error. Here a single object is created and it is used through out the program.

Comments