I am trying to get the battery status of the device in my app.
after having installed
cordova-plugin-battery-status
@ionic-native/battery-status
@ionic-native/core
I put BatteryStatus
into the module providers.
In the component, I have :
batterySubscription: Subscription;
batteryLevel: number = 100;
isBatteryPlugged: boolean = false;
constructor(private batteryStatus: BatteryStatus) { }
ngOnInit() {
this.initSubscriptions();
}
initSubscriptions() {
this.batterySubscription = this.batteryStatus.onChange().subscribe( (status:
BatteryStatusResponse) => {
console.log(status.level, status.isPlugged);
this.batteryLevel = status.level;
this.isBatteryPlugged = status.isPlugged;
});
}
Everything compiled perfectly, but the battery informations never change (as well in the browser as in the app). It doesn't detect neither when I plug the computer nor when the battery level changes.
Has somebody an idea of the problem ? Thanks !
CodePudding user response:
The code looks good to me, but that plugin is so old that it might not be working as expected on newer OSs. You can try and open an issue: https://github.com/apache/cordova-plugin-battery-status/issues
If I were you however, I'd try using capacitor: https://capacitorjs.com/docs/apis/device#getbatteryinfo
CodePudding user response:
Depending on the OS you are testing this with, instead of
this.battery.onChange()
you may get better results from
fromEvent<BatteryStatusResponse>(window, 'batterystatus')
This is what I have been using with Android 10, and have had the desired behavior from it.
For more reference: https://github.com/apache/cordova-plugin-battery-status/issues/66#issuecomment-527070672