iOS Question GetBatteryLevel

Filippo

Expert
Licensed User
Longtime User
Hi,

with this function "GetBatteryLevel" of Erel you can query the battery status, the question is how should it be queried, with a timer or via a notification?
In case of notification, how to create this notification?

I found this code (here), but I do not know how to convert it to B4i.
Is anyone familiar with this?

B4X:
override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: Selector(("batteryStateDidChange:")), name: NSNotification.Name.UIDeviceBatteryStateDidChange, object: nil)
    NotificationCenter.default.addObserver(self, selector: Selector(("batteryLevelDidChange:")), name: NSNotification.Name.UIDeviceBatteryLevelDidChange, object: nil)

    // Stuff...
}

func batteryStateDidChange(notification: NSNotification){
    // The stage did change: plugged, unplugged, full charge...
}

func batteryLevelDidChange(notification: NSNotification){
    
    let batteryLevel = UIDevice.current.batteryLevel
    if batteryLevel < 0.0 {
        print(" -1.0 means battery state is UIDeviceBatteryStateUnknown")
        return
    }
    
    print("Battery Level : \(batteryLevel * 100)%")
    // The battery's level did change (98%, 99%, ...)
}
 
Solution
To query the battery status after a notification would be better, but if it is not possible, then I guess I have to use a timer. The solution is not elegant, but it works.

Filippo

Expert
Licensed User
Longtime User
To query the battery status after a notification would be better, but if it is not possible, then I guess I have to use a timer. The solution is not elegant, but it works.
 
Upvote 0
Solution
Top