Kamran224
Kamran224

Reputation: 1614

Android wait till animation is completed

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

Answers (2)

Blackbelt
Blackbelt

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

user647826
user647826

Reputation:

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.

Upvotes: -1

Related Questions