1 /*
2  * Copyright 2019, The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.android.managedprovisioning.common;
17 
18 import static com.android.internal.util.Preconditions.checkNotNull;
19 
20 import android.graphics.drawable.Animatable2;
21 import android.graphics.drawable.AnimatedVectorDrawable;
22 import android.graphics.drawable.Drawable;
23 import android.os.Handler;
24 
25 /**
26  * A repeating {@link AnimatedVectorDrawable} animation.
27  */
28 public class RepeatingVectorAnimation {
29     /** Repeats the animation once it is done **/
30     private final Animatable2.AnimationCallback mAnimationCallback =
31         new Animatable2.AnimationCallback() {
32             @Override
33             public void onAnimationEnd(Drawable drawable) {
34                 if (mShouldLoop) {
35                     mUiThreadHandler.post(mAnimatedVectorDrawable::start);
36                 }
37             }
38         };
39 
40     private final Handler mUiThreadHandler = new Handler();
41     private final AnimatedVectorDrawable mAnimatedVectorDrawable;
42     private final boolean mShouldLoop;
43 
RepeatingVectorAnimation(AnimatedVectorDrawable animatedVectorDrawable)44     public RepeatingVectorAnimation(AnimatedVectorDrawable animatedVectorDrawable) {
45         this(animatedVectorDrawable, /* shouldLoop */ true);
46     }
47 
RepeatingVectorAnimation(AnimatedVectorDrawable animatedVectorDrawable, boolean shouldLoop)48     public RepeatingVectorAnimation(AnimatedVectorDrawable animatedVectorDrawable,
49             boolean shouldLoop) {
50         mAnimatedVectorDrawable = checkNotNull(animatedVectorDrawable);
51         mShouldLoop = shouldLoop;
52     }
53 
start()54     public void start() {
55         // Unregister callback in case it was already registered. Otherwise we get multiple
56         // calls of the same callback.
57         mAnimatedVectorDrawable.unregisterAnimationCallback(mAnimationCallback);
58         mAnimatedVectorDrawable.registerAnimationCallback(mAnimationCallback);
59         mAnimatedVectorDrawable.reset();
60         mAnimatedVectorDrawable.start();
61     }
62 
stop()63     public void stop() {
64         mAnimatedVectorDrawable.stop();
65         mAnimatedVectorDrawable.unregisterAnimationCallback(mAnimationCallback);
66     }
67 }
68