UIDeviceBatteryStateDidChangeNotification not work

2019-09-01 07:35发布

问题:

I am working on a Cordova app and I need to know the initial state of the battery and get a notification when the state changes. I am using iOS 8 on an iPod Touch 5g.

I am getting the code from: https://github.com/apache/cordova-plugin-battery-status/blob/master/src/ios/CDVBattery.m, so it should work...

I do this in AudioController.mm:

#import "AudioController.h"
#import <UIKit/UIKit.h>
#import <AVFoundation/AVAudioSession.h>
#import <MediaPlayer/MPMusicPlayerController.h>
#import <AudioToolbox/AudioToolbox.h>

@implementation AudioController

+(void)initializeAudio
{

    //Battery state detection
    if ([UIDevice currentDevice].batteryMonitoringEnabled == NO) {
        [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];


        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateBatteryStatus:) name:UIDeviceBatteryStateDidChangeNotification object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateBatteryStatus:) name:UIDeviceBatteryLevelDidChangeNotification object:nil];

    }

    //Initial state

    UIDevice* currentDevice = [UIDevice currentDevice];
    UIDeviceBatteryState currentState = [currentDevice batteryState];

    batteryState = NO; // UIDeviceBatteryStateUnknown or UIDeviceBatteryStateUnplugged
    if ((currentState == UIDeviceBatteryStateCharging) || (currentState == UIDeviceBatteryStateFull)) {
        batteryState = YES;
    }

    batteryLevel = 100 * [currentDevice batteryLevel];

}

//Battery detection

+ (void)updateBatteryStatus:(NSNotification*)notification
{
    UIDevice* currentDevice = [UIDevice currentDevice];
    UIDeviceBatteryState currentState = [currentDevice batteryState];

    batteryState = NO; // UIDeviceBatteryStateUnknown or UIDeviceBatteryStateUnplugged
    if ((currentState == UIDeviceBatteryStateCharging) || (currentState == UIDeviceBatteryStateFull)) {
        batteryState = YES;
    }

    batteryLevel = 100 * [currentDevice batteryLevel];

}

In AudioController.h

@protocol AudioControllerDelegate;

@interface AudioController : NSObject 

+(void)initializeAudio;
+ (void)updateBatteryStatus:(NSNotification*)notification;

@end

I am getting the current state and the level but the method named updateBatteryStatus isn't called. Why is that?

PS: I am also using this:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:) name:AVAudioSessionRouteChangeNotification object:nil];

to detect when the headphones are plugged in and this works.

PS2: I also have other methods there but those are the ones related to this problem.