2015-09-21 12 views
6

Vorrei avere il mio monitor dell'app quando il telefono è bloccato e sbloccato, così come quando si spegne (dopo una lunga inattività), tutto questo mentre la mia app non è a fuoco, ma in esecuzione in background.Come ascoltare l'evento di blocco/sblocco del telefono mentre l'applicazione è in esecuzione in background?

posso ricevere/sblocco/eventi vuoti di blocco con facilità, mentre app si concentra:

-(void) startListeningForPhoneLockEvent 
{ 
    NSLog(@"Start listening to lock/unlock and screen-goes-black events."); 

    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), 
           (void*)self, 
           lockStateChanged, 
           CFSTR("com.apple.springboard.lockstate"), 
           NULL, 
           CFNotificationSuspensionBehaviorDeliverImmediately); 

    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), 
           (void*)self, 
           hasBlankedScreen, 
           CFSTR("com.apple.springboard.hasBlankedScreen"), 
           NULL, 
           CFNotificationSuspensionBehaviorDeliverImmediately); 
} 

E callback funzioni:

static void lockStateChanged(CFNotificationCenterRef center, void*observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) 
{ 
    NSLog(@"Lock event received!"); 
} 

static void hasBlankedScreen(CFNotificationCenterRef center, void*observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) 
{ 
    NSLog(@"Blanked screen event received!"); 
} 

Io ho abilitato la modalità di sfondo:

  • Recupero sfondo.

Tuttavia, una volta che l'app va in background, non riceve eventi di blocco/sblocco/schermo vuoto.

Ho provato con altre modalità di sfondo, come la riproduzione audio, gli aggiornamenti di posizione ecc. Ma l'app non sta ancora ricevendo eventi di blocco/sblocco/schermo vuoto quando è in background.

Non sono sicuro che sia effettivamente possibile, o se sto facendo qualcosa di sbagliato.

Lo sto testando su un dispositivo reale che viene aggiornato a iOS9, utilizzando l'ultimo XCode con iOS9 SDK.

+0

Non mi dispiacerebbe nemmeno una soluzione in Swift. –

+0

Non è utile avere la modalità background abilitata nell'applicazione, l'applicazione dovrebbe essere effettivamente in esecuzione in background. Puoi confermare che l'applicazione è effettivamente in esecuzione in background quando si blocca/sblocca il telefono? – user3334059

+0

@SumantHanumante, ci sono restrizioni su Apple in esecuzione in background, ascolto di blocco, sblocco eventi? –

risposta

-1

Anche se l'app è configurata per l'esecuzione in background, non verrà effettivamente eseguita se non ha lavoro da svolgere. Per farlo funzionare in background con gli aggiornamenti di posizione, seguire these instructions by Ricky:

  1. ho riavviare il location manager ogni 1 minuto in funzione didUpdateLocations.
  2. Consente al responsabile della posizione di ottenere le posizioni dal dispositivo per 10 secondi prima di spegnerlo (per risparmiare batteria).

Codice parziale Sotto:

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ 

for(int i=0;i<locations.count;i++){ 
    CLLocation * newLocation = [locations objectAtIndex:i]; 
    CLLocationCoordinate2D theLocation = newLocation.coordinate; 
    CLLocationAccuracy theAccuracy = newLocation.horizontalAccuracy; 
    NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow]; 

    if (locationAge > 30.0) 
     continue; 

    //Select only valid location and also location with good accuracy 
    if(newLocation!=nil&&theAccuracy>0 
     &&theAccuracy<2000 
     &&(!(theLocation.latitude==0.0&&theLocation.longitude==0.0))){ 
     self.myLastLocation = theLocation; 
     self.myLastLocationAccuracy= theAccuracy; 
     NSMutableDictionary * dict = [[NSMutableDictionary alloc]init]; 
     [dict setObject:[NSNumber numberWithFloat:theLocation.latitude] forKey:@"latitude"]; 
     [dict setObject:[NSNumber numberWithFloat:theLocation.longitude] forKey:@"longitude"]; 
     [dict setObject:[NSNumber numberWithFloat:theAccuracy] forKey:@"theAccuracy"]; 
     //Add the vallid location with good accuracy into an array 
     //Every 1 minute, I will select the best location based on accuracy and send to server 
     [self.shareModel.myLocationArray addObject:dict]; 
    } 
} 

//If the timer still valid, return it (Will not run the code below) 
if (self.shareModel.timer) 
    return; 

self.shareModel.bgTask = [BackgroundTaskManager sharedBackgroundTaskManager]; 
[self.shareModel.bgTask beginNewBackgroundTask]; 

//Restart the locationMaanger after 1 minute 
self.shareModel.timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self 
                 selector:@selector(restartLocationUpdates) 
                 userInfo:nil 
                 repeats:NO]; 

//Will only stop the locationManager after 10 seconds, so that we can get some accurate locations 
//The location manager will only operate for 10 seconds to save battery 
NSTimer * delay10Seconds; 
delay10Seconds = [NSTimer scheduledTimerWithTimeInterval:10 target:self 
               selector:@selector(stopLocationDelayBy10Seconds) 
               userInfo:nil 
               repeats:NO]; 
} 

sono stato in grado di utilizzare il codice nel progetto github riferimento in là per ascoltare il bloccare e sbloccare gli eventi su un dispositivo con iOS 9, utilizzando il ultimo XCode. Ecco i registri:

2015-12-18 13:31:44.777 Location[16185:3796448] startLocationTracking 
2015-12-18 13:31:44.780 Location[16185:3796448] authorizationStatus authorized 
2015-12-18 13:31:44.788 Location[16185:3796448] Start listening to lock/unlock and screen-goes-black events. 
2015-12-18 13:31:44.834 Location[16185:3796448] locationManager didUpdateLocations 
2015-12-18 13:31:44.837 Location[16185:3796448] started master task 1 
2015-12-18 13:31:45.197 Location[16185:3796448] locationManager didUpdateLocations 
2015-12-18 13:31:48.079 Location[16185:3796448] Blanked screen event received! 
2015-12-18 13:31:48.215 Location[16185:3796448] Lock event received!
+0

Qualcuno può spiegare perché questa risposta è stata downvoted? Ho provato ad aggiungere un commento e ho detto che non avevo abbastanza karma e potevo solo aggiungere una risposta – user3272750

Problemi correlati