Android How to increase Battery level in text view

I’d suggest using the postDelayed(...) method of the View class and also don’t use an actual BroadcastReceiver.

For example, Intent.ACTION_BATTERY_CHANGED is a STICKY broadcast and as such doesn’t need a BroadcastReceiver to handle it. Instead if we pass null as the first parameter to the registerReceiver(...) method, no receiver is actually registered but the return from that call is the Intent from the sticky broadcast. Example…

Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

The next step is to setup the 5 second update for the TextView. The Android View class has a postDelayed(...) method which accepts a Runnable parameter as well as a delay in milliseconds. Example…

textBatteryLevel.postDelayed(levelChecker, 5000);

The postDelayed(...) method of View is a one-shot (non-repeating) ‘post’ so make sure it is reset within the run() method of the Runnable each time it is called.

I haven’t tested the following code but I think it should work. Bear in mind however, there’s no guarantee that the level of battery charge will change within any 5 second period. It probably takes about 1 minute per 1% to charge my tablet and similar on my phone so I certainly wouldn’t expect to see an update to the TextView every 5 seconds.

public class ChargingActivity extends Activity {

    TextView textBatteryLevel = null;
    int level;
    LevelChecker levelChecker = new LevelChecker();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chargingactivity);
        textBatteryLevel = (TextView) findViewById(R.id.btrylevel);

        // Get the current battery level
        Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);

        // Set the starting level
        textBatteryLevel.setText(String.valueOf(level) + "%");
    }

    @Override
    protected void onResume() {
        super.onResume();
        textBatteryLevel.postDelayed(levelChecker, 5000);
    }

    @Override
    protected void onPause() {
        textBatteryLevel.removeCallbacks(levelChecker);
    }

    private class LevelChecker extends Runnable {

        @Override
        public void run() {
            Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            int currentLevel = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
            if (currentLevel != level) {
                level = currentLevel;
                textBatteryLevel.setText(String.valueOf(level) + "%");
            }
            textBatteryLevel.postDelayed(levelChecker, 5000);
        }
    }

}

Leave a Comment