【问题标题】:How to detect if the device has just been rebooted?如何检测设备是否刚刚重新启动?
【发布时间】:2018-07-18 06:28:30
【问题描述】:

我有一个应用程序可以间隔提供数据使用。我想在使用数据使用之前检测设备是否已重新启动。我尝试使用 mach_absolute_time() 但我什么都听不懂。这可能吗?

【问题讨论】:

    标签: ios


    【解决方案1】:

    您可以像这样获得系统正常运行时间:

    let systemUptime = NSProcessInfo.processInfo().systemUptime; // swift
    NSTimeInterval timeInterval = [NSProcessInfo processInfo].systemUptime; //Objective c
    

    您可以将其存储在 NSUserDefaults 中并使用它来确定是否发生了重启。

    请查看this 线程以获取更多信息。

    斯威夫特 3:

    let systemUptime: TimeInterval = ProcessInfo.processInfo.systemUptime
    

    【讨论】:

    • 当用户更改手机的日期/时间时,所有这些技术都会检测到重启。这些技术仅适用于可靠的系统启动时间戳,如果该信息可用,则不需要这些黑客攻击。
    • @piojo 该信息不是明确可用的,但可以很容易地计算出来;在下面查看我的答案
    【解决方案2】:

    这是我制作的。它需要 GMT 的当前时间和自上次重新启动以来的时间来推断设备上次重新启动的日期。然后它使用 NSUserDefaults 在内存中跟踪这个日期。享受吧!

    #define nowInSeconds CFAbsoluteTimeGetCurrent()//since Jan 1 2001 00:00:00 GMT
    #define secondsSinceDeviceRestart ((int)round([[NSProcessInfo processInfo] systemUptime]))
    #define storage [NSUserDefaults standardUserDefaults]
    #define DISTANCE(__valueOne, __valueTwo) ((((__valueOne)-(__valueTwo))>=0)?((__valueOne)-(__valueTwo)):((__valueTwo)-(__valueOne)))
    
    +(BOOL)didDeviceReset {
        static BOOL didDeviceReset;
        static dispatch_once_t onceToken;
        int currentRestartDate = nowInSeconds-secondsSinceDeviceRestart;
        int previousRestartDate = (int)[((NSNumber *)[storage objectForKey:@"previousRestartDate"]) integerValue];
        int dateVarianceThreshold = 10;
        dispatch_once(&onceToken, ^{
            if (!previousRestartDate || DISTANCE(currentRestartDate, previousRestartDate) > dateVarianceThreshold) {
                didDeviceReset = YES;
            } else {
                didDeviceReset = NO;
            }
        });
        [storage setObject:@(currentRestartDate) forKey:@"previousRestartDate"];
        [storage synchronize];
        return didDeviceReset;
    }
    

    【讨论】:

    • 不要使用-[NSUserDefaults synchronize]。来自Apple's documentation“这个方法是不必要的,不应该使用。”。另外,不要对多个问题给出相同的答案。只需在 cmets 中提供一个链接。 stackoverflow.com/a/51391327/123632
    • @AshleyMills 我们的应用程序支持 iOS6+,因此我们需要同步以防用户在不久之后进入后台(尝试强制退出应用程序以绕过设备重置检测)。同步在 iOS7 之后才变得不必要。请不要对这样的事情投反对票
    猜你喜欢
    • 2017-05-09
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 2012-09-11
    • 2012-10-19
    相关资源
    最近更新 更多