4

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.

Pascal Piché
  • 600
  • 2
  • 13
Kamran224
  • 1,584
  • 7
  • 20
  • 33

2 Answers2

8

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

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
-1

Suggest you

  • Create an object to encapsulate the "animation" lifetime
  • In the object, you'll have a thread OR a Timer
  • Provide methods to start() the animation and awaitCompletion()
  • Use a private final Object 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.