UIDeviceBatteryStateDidChangeNotification not working on iOS 8

空扰寡人 提交于 2019-12-11 18:08:25

问题


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.

来源:https://stackoverflow.com/questions/26617434/uidevicebatterystatedidchangenotification-not-working-on-ios-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!