summaryrefslogtreecommitdiff
path: root/external/plyer/platforms/android/battery.py
blob: 2ade1d25c49280295d68d3ccb6fef5a831f25952 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from jnius import autoclass, cast
from plyer.platforms.android import activity
from plyer.facades import Battery

Intent = autoclass('android.content.Intent')
BatteryManager = autoclass('android.os.BatteryManager')
IntentFilter = autoclass('android.content.IntentFilter')


class AndroidBattery(Battery):
    def _get_state(self):
        status = {"isCharging": None, "percentage": None}

        ifilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)

        batteryStatus = cast('android.content.Intent',
            activity.registerReceiver(None, ifilter))

        query = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1)
        isCharging = (query == BatteryManager.BATTERY_STATUS_CHARGING or
                     query == BatteryManager.BATTERY_STATUS_FULL)

        level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
        scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
        percentage = level / float(scale)

        status['isCharging'] = isCharging
        status['percentage'] = percentage

        return status


def instance():
    return AndroidBattery()