I am creating an Idle fighting game through Android Studio Java which requires running a lot of attacking/general combat animations in sequence. I am using ExecutorService instantiated through SingleThreadExecutor to execute Runnables containing animation code.
Example code excerpt:
//list of animations to run.
LinkedList<Runnable> animationTasks = new LinkedList<>();
//example add an animation to the list.
animationTasks.add(animateMissOnTarget(target);
//how the animations are executed in sequence.
ExecutorService executor = newSingleThreadExecutor();
for (Runnable animation : animationTasks) {
executor.execute(animation);
}
//example animation runnable.
private Runnable animateMissOnTarget(String target) {
return new Runnable() {
@Override
public void run() {
View targetCombatantView = combatantViewLookup.get(target);
ImageView missImageView = targetCombatantView.findViewById(R.id.combatant_miss_image);
missImageView.post(()-> {
missImageView.setVisibility(View.VISIBLE);
((AnimationDrawable) missImageView.getBackground()).start();
});
try {
sleep(combatSpeed);
} catch (InterruptedException e) {
e.printStackTrace();
findViewById(R.id.interrupted).setVisibility(View.VISIBLE);
}
missImageView.post(()-> {
missImageView.setVisibility(View.INVISIBLE);
((AnimationDrawable) missImageView.getBackground()).stop();
});
}
};
}
Sometimes (although rarely) the phone's entire main (UI) thread freezes and stops responding which is a pretty big bug for a game to have.
Unsure if I've done this in a very silly way. Does anyone know if there's a better way through Android to display lots of animations in a row rather than the method I am going with?
Thanks all :)
I have rewritten the code multiple times to reduce dynamic loading of drawables and such which has reduced the frequency of the bug, however it still persists so I am wondering if it is something more core to Android OS, like the OS killing off threads to save CPU etc