Reputation: 1614
I am moving an image and I want to play a sound file after the object's animation is completed
The image moves but I tried using Threads to wait until a duration but it didn't work.
Animation animationFalling = AnimationUtils.loadAnimation(this, R.anim.falling);
iv.startAnimation(animationFalling);
MediaPlayer mp_file = MediaPlayer.create(this, R.raw.s1);
duration = animationFalling.getDuration();
mp_file.pause();
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(duration);
mp_file.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Thanks.
Upvotes: 4
Views: 5909
Reputation: 157437
you can register a delegate for the animation:
animationFalling.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
// here you can play your sound
}
);
you can read more about the AnimationListener here
Upvotes: 8
Reputation:
Suggest you
awaitCompletion()
completionMonitor
field to track completion, synchronize on it, and use wait() and notifyAll()
to
coordinate the awaitCompletion()Code snippet:
final class Animation {
final Thread animator;
public Animation()
{
animator = new Thread(new Runnable() {
// logic to make animation happen
});
}
public void startAnimation()
{
animator.start();
}
public void awaitCompletion() throws InterruptedException
{
animator.join();
}
}
You could also use a ThreadPoolExecutor
with a single thread or ScheduledThreadPoolExecutor
, and capture each frame of the animation as a Callable. Submitting the sequence of Callables and using invokeAll() or a CompletionService
to block your interested thread until the animation is complete.
Upvotes: -1