are android animations always within the UI Thread?

Viewed 11167

I'd like to clarify using of view, propery, etc. animations in Android.

Usually, I create animation without any Tread's things - directly within my Activity/Fagment/ViewClass:

AlphaAnimation alphaAnimation = new AlphaAnimation(0,1);
alphaAnimation.setDuration(100);
mView.setAnimation(alphaAnimation);
alphaAnimation.start();

I understand this as an animation executing within main UI thread.

But if I will create an animation within a worker thread - will it be normal way?

public void onClick(View v) {
  new Thread(new Runnable() {
    public void run() {
      final AlphaAnimation alphaAnimation = new AlphaAnimation(0,1);
      alphaAnimation.setDuration(100);
      mView.post(new Runnable() {
        public void run() {
          mView.setAnimation(alphaAnimation);
          alphaAnimation.start();
        }
      });
    }
  }).start();
}
2 Answers

Expanding on Doug's answer, and the explanations in the comments to his answer -

For maintaining a frame rate of 60 fps for smooth transitions and animations, we have ≈ 16 ms/frame to bring a frame to the screen. In these 16 ms, all sorts of things need to be done, including but not limited to processing user input, processing animations, measurement & laying out of different views, preparing and issuing display lists to the GPU, compositing windows, and finally displaying the output on the screen. And there is no time limit specifically for the animation stage (or any of the stages).

Also, only a specific amount of work needs to be done per frame per animation. For example, to rotate a view by 180 degrees in 1 s, we need to make calculations to rotate it by 3 degrees per frame. And this calculation is not interrupted in case it exceeds some time limit (even 16 ms). However if the entire process of frame rendering is unable to execute in 16 ms, then we see a frame drop.

Now if one of the stages takes too long to execute, it is possible to run them in a worker thread to free up the UI thread for other stages. But there's a catch - you cannot manipulate components from the Android UI toolkit (components from the android.widget and android.view packages) from a worker thread. So Android provides a post() method, to schedule methods from the worker thread to run on the UI thread. Refer to https://developer.android.com/guide/components/processes-and-threads for more on this topic.

Now what you are doing is not helping much, because as Doug said, you're scheduling the animation runnable to execute on the main thread. The only work done in the worker thread is

final AlphaAnimation alphaAnimation = new AlphaAnimation(0,1);
alphaAnimation.setDuration(100);

which is not particularly resource intensive, hence there is not much to gain by putting it in a separate thread.

Related