2009-05-08 25 views
23

no puedo encontrar nada concreto utilizando my favourite tool, sin embargo pensé que iba a ponerlo aquí ...Detectar si el dispositivo se está cargando

¿Hay alguna manera, utilizando el SDK del iPhone, una aplicación para detectar si el dispositivo está en un estado de recepción de energía (carga, muelle, etc.)?

Me gustaría poder desactivar el idleTimer automáticamente si el dispositivo está recibiendo alimentación (de lo contrario, es una configuración especificada por el usuario).

+0

Buen toque para vincular Google, me reí. Buena pregunta, me ahorró tiempo. Gracias a ti y a los contribuyentes. –

Respuesta

32

Sí, UIDevice es capaz de decirle esto:

[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES]; 

if ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateCharging) { 
    NSLog(@"Device is charging."); 
} 

Véase la referencia UIDevice en la documentación para obtener más información y para otros valores de batteryState.

39

Usted es mejor de usar:

[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES]; 

if ([[UIDevice currentDevice] batteryState] != UIDeviceBatteryStateUnplugged) { 
     [UIApplication sharedApplication].idleTimerDisabled=YES; 
    } 

Esto se debe a que tiene que preocuparse por dos estados diferentes - uno es que la batería está cargando, y el otro cuando es totalmente cargado.

Si realmente quería finalizar con esto - le registrarse para recibir notificaciones de supervisión de la batería, por lo que podría volver a activar el temporizador de inactividad si el usuario desconecta la alimentación principal, etc.

0

Se puede utilizar darwin notification center y use el nombre del evento com.apple.springboard.fullycharged.

De esta manera obtendrá una notificación a su método personalizado, aquí es una sección de código:

// Registering for a specific notification 
NSString *notificationName = @"com.apple.springboard.fullycharged"; 
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), 
           NULL, 
           yourCustomMethod, 
           (__bridge CFStringRef)notificationName, 
           NULL, 
           CFNotificationSuspensionBehaviorDeliverImmediately); 

// The custom method that will receive the notification 
static void yourCustomMethod(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) 
{ 
    NSString *nameOfNotification = (__bridge NSString*)name; 

    if([nameOfNotification isEqualToString:notificationName]) 
    { 
    // Do whatever you want... 
    } 
} 
+1

La respuesta es iOS ... debe probar el código de recorte. Lo usé en algunos proyectos míos. Además, lea los hipervínculos arriba. – OhadM

4

Swift

UIDevice.currentDevice().batteryMonitoringEnabled = true; 

if (UIDevice.currentDevice().batteryState != .Unplugged) { 
    print("Device is charging."); 
} 
4

Swift 3:

UIDevice.current.isBatteryMonitoringEnabled = true 
let state = UIDevice.current.batteryState 

if state == .charging || state == .full { 
    print("Device plugged in.") 
} 
+0

puede ser, es "dejar estado = UIDevice.current.batteryState" –

+1

@BateroBui y todos los que sugirieron la actualización; Gracias – UpSampler

Cuestiones relacionadas