iPhone:检测自上次屏幕触摸后用户不活动/空闲时间 [英] iPhone: Detecting user inactivity/idle time since last screen touch

查看:80
本文介绍了iPhone:检测自上次屏幕触摸后用户不活动/空闲时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有人实施了一项功能,如果用户在一段时间内没有触摸屏幕,您会采取某种行动吗?我正在试图找出最好的方法。

Has anybody implemented a feature where if the user has not touched the screen for a certain time period, you take a certain action? I'm trying to figure out the best way to do that.

在UIApplication中有一些与此有关的方法:

There's this somewhat-related method in UIApplication:

[UIApplication sharedApplication].idleTimerDisabled;

如果您改为这样的话会很好:

It'd be nice if you instead had something like this:

NSTimeInterval timeElapsed = [UIApplication sharedApplication].idleTimeElapsed;

然后我可以设置一个计时器并定期检查这个值,并在超过a时采取一些措施门槛。

Then I could set up a timer and periodically check this value, and take some action when it exceeds a threshold.

希望这能解释我在寻找什么。有没有人已经解决过这个问题,或者对你将如何做到这一点有任何想法?谢谢。

Hopefully that explains what I'm looking for. Has anyone tackled this issue already, or have any thoughts on how you would do it? Thanks.

推荐答案

以下是我一直在寻找的答案:

Here's the answer I had been looking for:

让您的应用程序委托子类UIApplication。在实现文件中,覆盖sendEvent:方法,如下所示:

Have your application delegate 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");
}

其中maxIdleTime和idleTimer是实例变量。

where maxIdleTime and idleTimer are instance variables.

为了使其正常工作,您还需要修改main.m以告诉UIApplicationMain使用您的委托类(在此示例中为AppDelegate)作为主要类:

In order for this to work, you also need to modify your main.m to tell UIApplicationMain to use your delegate class (in this example, AppDelegate) as the principal class:

int retVal = UIApplicationMain(argc, argv, @"AppDelegate", @"AppDelegate");

这篇关于iPhone:检测自上次屏幕触摸后用户不活动/空闲时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆