Android is waiting for the animation to complete
I move the image and I want to play the sound file after the animation of the object finishes.
The image is moving, but I tried to use Threads to wait until it continues, 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();
Thank.
+3
source to share
2 answers
you can register a delegate for 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 AnimationListener here
+7
source to share
Suggest you
- Create an object to encapsulate the animation lifecycle
- In an object you will have a thread or a timer
- Provide methods to start () the animation and
awaitCompletion()
- Use a private target Object
completionMonitor
to track completion, sync on it, and usewait() and notifyAll()
to coordinate waitingCompletion ()
Snippet of code:
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 can also use ThreadPoolExecutor
with a single thread or ScheduledThreadPoolExecutor
and capture each frame of the animation as Callable. Sending a Callables sequence and using invokeAll() or a CompletionService
it to block your thread of interest until the animation finishes.
-1
user647826
source
to share