我们想构建一个应用程序,将监控我们拥有的每台设备的电池作为后台活动,并每小时将该信息上传到服务器。通过这种方式,我们将能够知道何时需要为设备充电。
我不确定如何在应用程序处于后台时获取此信息。如果它不活跃,我似乎没有收到通知。这可能吗?如果有任何帮助,这是我的代码。
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
// Request to be notified when battery charge or state changes
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryStatus) name:UIDeviceBatteryLevelDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryStatus) name:UIDeviceBatteryStateDidChangeNotification object:nil];
- (void)batteryStatus
{
NSArray *batteryStatus = [NSArray arrayWithObjects:
@"Battery status is unknown.",
@"Battery is in use (discharging).",
@"Battery is charging.",
@"Battery is fully charged.", nil];
// if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground)
// [self notifyServer];
// do something. this is never called when in background.
if ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateUnknown)
{
[textViewStatus setText:[batteryStatus objectAtIndex:0]];
NSLog(@"%@", [batteryStatus objectAtIndex:0]);
}
else
{
NSString *msg = [NSString stringWithFormat:
@"Battery charge level: %0.2f%%\n%@", [[UIDevice currentDevice] batteryLevel] * 100,
[batteryStatus objectAtIndex:[[UIDevice currentDevice] batteryState]] ];
[textViewStatus setText:msg];
NSLog(@"%@", msg);
}
}