Android ObjectAnimator independent of global animator duration

Until now, I have released two Android games Snowflakes Fight Back  and Facts No Yes and I am working on my third game. Contrary to all recommendations, these games are written in Java using the classic Android SDK, I mean I use ImageView and ObjectAnimator instances. I have a good reason to do this, but I will tell you about it another time. In this post I will talk about how you can make ObjectAnimator animation duration independent of global animator duration scale setting in the developer options.

The problem is that ObjectAnimator can be disabled by default on some low end devices. These devices are actually totally capable to run my game but the manufacturer decided to disable Android animations to make the device look more snappy. More than that, you can change the animation duration scale yourself, making the animations run faster or slower. This is good for UI but it’s really bad for a game. So how can I make sure my games run the same on any device regardless of the global animator duration scale?

As a matter of fact, there is a hidden API in the Android SDK that can be accessed via reflection. With this hidden API you can override the global duration scale settings for your application only. Basically you can make sure your animations run the same on any device. The code is as follows:

// Get duration scale from the global settings.
float durationScale = Settings.Global.getFloat(context.getContentResolver(),
                        Settings.Global.ANIMATOR_DURATION_SCALE, 0);

// If global duration scale is not 1 (default), try to override it
// for the current application.
if (speed != 1) {
  try {
    Class c;
    c = Class.forName("android.animation.ValueAnimator");
    Method m = c.getMethod("setDurationScale", new Class[]{float.class});
    Object o = m.invoke(null, new Object[]{ 1f });
    durationScale = 1f;
  } catch (Throwable t) {
    // It means something bad happened, and animations are still
    // altered by the global settings. You should warn the user and
    // exit application.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s