Reputation: 7981
Beginner here, I have a simple question.
In Android what would be the best what to check for something at regular intervals?
Please bear with me, I'll try to explain the best I can --
For example my audio app is very simple, a main activity and a service. The main activity has a UI with two buttons, start and stop audio. I press start and the audio service starts. Likewise when I click Stop the service stops and the audio ends. If isLooping()
is hard-coded to true there is no issue because the audio never ends unless I hit stop button, which stops the audio service and also resets the button states.
This is an issue now because I set isLooping()
to false so the audio doesn't loop. So the audio will stop playing but the service is still running.
I want to be able to detect when the audio stops so I can set the states of the UI buttons. So I need something that is always checking whether audio is playing (i.e. check player.isPlaying()
so I can end the service and set the enable/disable state of the buttons.
I figured out binding to the service so I can access the MediaPlayer
controls via my main activity so I know the code to check if it's playing, but WHERE do I put this code so it's checked all the time?
Am I making sense? I know this is probably very simple. Thanks for any help.
Upvotes: 4
Views: 1493
Reputation: 1972
You can repeat it with the TimerTask and Timer. Code below:
public final void RepeatSoundFunction(){
t = new Timer();
tt = new TimerTask() {
@Override
public void run() {
mp.seekTo(0); //Reset sound to beginning position
mp.start(); //Start the sound
t.purge(); //Purge the sound
}
};
t.schedule(tt, 10*1000); //Schedule to run tt (TimerTask) again after 10 seconds
}
then you set a MediaPlayer onCompletionListener and in there you put this.
Inside the run-code you can check for other things than music, I just show an example with the audio.
Upvotes: 1