Pages

Wednesday, May 21, 2014

Detecting user inactivity/idle time since last touch on screen

Recently I required to find inactivity of screen in one of my project. I do this task by the subclass of UIApplication.Here is the steps by which I completed this task.

Step 1 -  Add a class(inactiveClass)  in your project which subclass UIApplication. In the implementation file, override the sendEvent: method like so:
- (void)sendEvent:(UIEvent *)event {
    [super sendEvent:event];

    // Only want to reset the timer on a Began touch or an Ended touch, to reduce the number of timer resets.
    NSSet *allTouches = [event allTouches];
    if ([allTouches count] > 0) {
        // allTouches count only ever seems to be 1, so anyObject works here.
        UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
        if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded)
            [self resetIdleTimer];
    }
}

- (void)resetIdleTimer {
    if (idleTimer) {
        [idleTimer invalidate];
        [idleTimer release];
    }

    idleTimer = [[NSTimer scheduledTimerWithTimeInterval:maxIdleTime target:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:NO] retain];
}

- (void)idleTimerExceeded {
    NSLog(@"idle time exceeded");
}

where maxIdleTime and idleTimer are instance variables.

Step 2 - In order for this to work, you also need to modify your main.m to tell UIApplicationMain to use your subclass

int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, @"inactiveClass", nil);
    }
}



No comments:

Post a Comment