Animation in status bar in Android

2019-02-20 11:56发布

问题:

I'm new here in Android. I'd like to make a Battery Charging Animation in the phone, for example, in the top-right of the screen, the small icon that is moving upside down when charging and stops on a current battery percentage.

So far in my code, I've been able to make it move, but it never stops.

What I want is for the animation to stop when it is not charging or for it to stop on a current battery percentage.

Here is my code in the animation :

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.batteryinfo);

        ImageView batteryImage = (ImageView) findViewById(R.id.BatteryImage);
        batteryImage.setBackgroundResource(R.drawable.ic_battery_animation);

        BatteryAnimation = (AnimationDrawable) batteryImage.getBackground();
        batteryImage.post(new Starter());

        textBatteryLevel = (TextView) findViewById(R.id.batterylevel_text);

        registerBatteryLevelReceiver();
    }

    class Starter implements Runnable {

        public void run() {
            BatteryAnimation.start();
        }

    }

So far, I can get the Battery Status, the Plug Type, and the Health of the Battery.

回答1:

Starter class should implement also stop logic. Something like:

class Starter implements Runnable {
    boolean stopConditionMet = false;
    public void run() {
        BatteryAnimation.start();
        try {
         while (!stopConditionMet) { Thread.sleep(500); } 
        } catch (InterruptedException e) {}
         BatteryAnimation.stop();

    }
    public void stop() { stopConditionMet=true; }

}

(instead of busy wait you can do this with wait()-notifyAll() scheme. The above example if for simplicity).

.. and you'll need to keep the instance of the Starter class inside your Activity. Declaring it anonymously won't allow you to change its value when you need.