下面是我为自定义的一些代码的简化View
。它有一个Runnable
用于动画和一个Runnable
用于音频。该start()
函数同时启动可运行的动画和可运行的音频。每个可运行对象都实现了一个带有完成回调的接口。
我需要知道两者什么时候完成,所以我可以打电话给onBothRunnablesFinished()
.
public class Foo extends View {
RunnableA mRunnableA;
RunnableB mRunnableB;
// overrides of onCreate, onMeasure, onDraw, etc...
private void onBothRunnablesFinished() {
// Do stuff when both runnables are finished...
}
public void start() {
mRunnableA = new RunnableA();
mRunnableB = new RunnableB();
post(mRunnableA);
post(mRunnableB);
}
private class RunnableA implements Runnable, AnimationListener {
private MyAnimation mAnim;
private boolean mRunning = false;
public RunnableA() {
mAnim = new MyAnimation();
mAnim.setAnimationListener(this);
}
public boolean isRunning() {
return mRunning;
}
@Override
public void run() {
mRunning = true;
startAnimation(mAnim);
}
// Called when mAnim finishes
@Override
public void onAnimationEnd(Animation animation) {
mRunning = false;
// **WHAT IF THE OTHER RUNNABLE FINISHES NOW?**
if (mRunnableB.isRunning() == false) {
onBothRunnablesFinished();
}
}
}
private class RunnableB implements Runnable, OnCompletionListener {
private MyMediaPlayer mMediaPlayer;
private boolean mRunning = false;
public RunnableB() {
mMediaPlayer = MyMediaPlayer();
mMediaPlayer.setOnCompletionListener(this);
}
public boolean isRunning() {
return mRunning;
}
@Override
public void run() {
mRunning = true;
mMediaPlayer.start();
}
// Called when mMediaPlayer finishes
@Override
public void onCompletion(MediaPlayer mp) {
mRunning == false;
// **WHAT IF THE OTHER RUNNABLE FINISHES NOW?**
if (mRunnableA.isRunning() == false) {
onBothRunnablesFinished();
}
}
}
}
我用评论标记了几个感兴趣的领域。如果音频和动画可运行文件同时完成会发生什么?更具体地说,一个可运行的回调是否会在上面注释的位置中断另一个的回调?这可能吗??
我希望不会,因为 thenonBothRunnablesFinished
会被调用两次。如果是这种情况,我该如何解决这个问题?