iOS APP闲置、超时提醒

由于最近要做某银联验证,其中要求客户端闲置多少时间后提示超时。
本来是要由服务端那边进行控制,最后反而决定由客户端这边来完成。

本方法主要继承UIApplication,重写sendEvent: 方法。
1、新建UIApplication子类
QQ20140710-1

2、定义2宏和NSTimer:
[objc]
#import <UIKit/UIKit.h>
#define kKDAppTimeOutSec 5 //触摸超时时间(秒)
#define kKDAppNName @"AppTimeOut" //通知名字
@interface KDApplication : UIApplication {

NSTimer *idleTimer;

}
@end
[/objc]

3、实现sendEvent:重写
[objc]
#import "KDApplication.h"

@implementation KDApplication

/** 屏幕触摸事件 */
-(void)sendEvent:(UIEvent *)event {

if (!idleTimer)
[self idleTimerInit];//首次触发,初始化计时器;

NSSet *allTouches = [event allTouches];
if ([allTouches count] > 0) {

UITouchPhase phase = ((UITouch *) [allTouches anyObject]).phase;
if (phase == UITouchPhaseBegan) {//开始触摸
[self idleTimerInit];
}

}

[super sendEvent:event];
}

-(void)idleTimerInit {

if (idleTimer)
[idleTimer invalidate];

idleTimer = [NSTimer scheduledTimerWithTimeInterval:kKDAppTimeOutSec
target:self
selector:@selector(idleTimerOutAction)
userInfo:nil
repeats:NO];

}

-(void)idleTimerOutAction{
//响应计时器
[[NSNotificationCenter defaultCenter] postNotificationName:kKDAppNName object:nil];
}

@end
[/objc]

4、修改main.m
[objc]
#import "AppDelegate.h"
#import "KDApplication.h"
int main(int argc, char *argv[])
{

@autoreleasepool {
return UIApplicationMain(argc, argv, NSStringFromClass([KDApplication class]), NSStringFromClass([AppDelegate class]));
}
}
[/objc]

5、加入通知
[objc]
#import "KDApplication.h"
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appTimeOutAction:) name:kKDAppNName object:nil];

-(void)appTimeOutAction:(NSNotification *)notification {
}
[/objc]

73 thoughts on “iOS APP闲置、超时提醒

Eimiej进行回复 取消回复

电子邮件地址不会被公开。