这就是我一直在寻找的答案:
让应用程序委托子类UIApplication.在实现文件中,重写sendEvent:方法,如下所示:
- (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");
}
其中maxIdleTime和idleTimer是实例变量.
为了使其正常工作,您还需要修改main.m以告诉UIApplicationMain使用您的委托类(在本例中为AppDelegate)作为主体类:
int retVal = UIApplicationMain(argc, argv, @"AppDelegate", @"AppDelegate");