我已经在这个问题上工作了几天,但一直无法解决这个问题。
我有许多动画都实现为 Runnables,当用户使用应用程序时,它们将持续运行。从 logo_animation000 到 115 和 z_animation000 到 515 有 4 种不同的动画:
- ConnectingAnimation(在应用程序连接到设备时运行)
- ConnectingCompleteAnimation(连接完成时运行一次)
- TransitiontoSleepingAnimation(当应用状态改变时运行一次)
- SleepingAnimation(在应用程序状态为:“Sleeping”时运行
这些动画太大而无法使用常规动画列表来工作,因此我被迫使用自己的实现。我用以下课程“解决”了这个问题:
abstract class MyAnimationRunnable implements Runnable {
protected final int interval;
protected final String pattern;
protected final OptimisedImageView view;
protected long firstFrameAt;
protected int current;
protected Drawable drawable;
protected int frameCounter = 0;
public MyAnimationRunnable(int interval, int firstFrame, String pattern, OptimisedImageView view) {
this.interval = interval;
this.pattern = pattern;
this.view = view;
this.current = firstFrame;
this.firstFrameAt = SystemClock.elapsedRealtime();
handler.post(this);
}
@Override
public void run() {
final String name = String.format(Locale.ENGLISH, pattern, current);
final int id = getResources().getIdentifier(name, "drawable", getPackageName());
if (id != 0) {
final Drawable drawable = getResources().getDrawable(id);
view.setImageDrawable(drawable);
}
current++;
if (runAgain()) {
frameCounter++;
long nextAt = firstFrameAt + (frameCounter * interval);
long delay = nextAt - SystemClock.elapsedRealtime() - 1;
if (delay > 0) {
handler.postDelayed(this, delay);
} else {
this.run();
}
}
}
protected abstract boolean runAgain();
};
private void startSleepingAnimation()
{
zzzAnimation = new MyAnimationRunnable(50, 1, "z_animation%04d", zzzImageView) {
@Override
protected boolean runAgain() {
if (current == 510) {
current = 470; // this seems to fit into the infinite loop.
}
return true;
}
};
}
private void startConnectingAnimation() {
handler.removeCallbacks(connectingCompleteAnimation);
handler.removeCallbacks(zzzAnimation);
handler.removeCallbacks(transitionToSleepingAnimation);
connectingResourceCount = 1;
zzzImageView.setImageBitmap(null);
connectingAnimation = new MyAnimationRunnable(50, connectingResourceCount, "logo_animation%04d", babyImageView) {
@Override
protected boolean runAgain() {
if (current == 30) {
current = 1;
}
connectingResourceCount = current;
return true;
}
};
}
// The remaining two animations have been left out since this oughta be sufficient for understanding the code.
这在我的三星 Galaxy S3 上运行良好。然而,在旧手机上,这会在 20-30 秒后导致崩溃。关于如何使这段代码更轻、更高效的任何想法?