androidbatterymanager

Android Battery Broadcasts


I am trying to make a Battery Alarm Application. I was reading the Android docs and found out that we don't need to register a BroadcastReceiver. We could do something like this-

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);

MY QUESTIONS ARE-


Solution

  • here is a full sample to get battery level

    private float getBatteryLevel() {
        Intent batteryStatus = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        int batteryLevel = -1;
        int batteryScale = 1;
        if (batteryStatus != null) {
          batteryLevel = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, batteryLevel);
          batteryScale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, batteryScale);
        }
        return batteryLevel / (float) batteryScale * 100;
      }
    

    answering your questions:

    1- Yes, you can get additional information by getExtra and define the key,BatteryManager has a lot of keys to extract information from the intent.

    2- no, you just have to register the reciever and unregister it accoording to the Activity or Fragment lifcycle, usually registering in onCreate()/onCreateView() and unregistering in onDestry()/onDestroyView().

    3- you can create a bound service that has a simple notification interface. you register your reciever on it, and from the previous sample you could do something like this:

    if (getBatteryLevel < 10) {
    //show notification or do whatever you want.
    }