【问题标题】:Can we call the method after the application has been minimized?我们可以在应用程序最小化后调用该方法吗?
【发布时间】:2013-07-09 13:18:57
【问题描述】:

iOS

我们可以在应用最小化后调用该方法吗?

例如,5秒后被调用applicationDidEnterBackground:

我使用这段代码,但是test 方法不调用

- (void)test
{
    printf("Test called!");
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [self performSelector:@selector(test) withObject:nil afterDelay:5.0];
}

【问题讨论】:

标签: iphone ios objective-c cocoa


【解决方案1】:

您可以在后台运行后使用后台任务 API 调用方法(只要您的任务不会花费太长时间 - 通常约 10 分钟是允许的最长时间)。

iOS 不会让计时器在应用处于后台时触发,因此我发现在应用处于后台之前调度后台线程,然后将该线程置于睡眠状态,与计时器具有相同的效果。

将以下代码放入您的应用委托的- (void)applicationWillResignActive:(UIApplication *)application 方法中:

// Dispatch to a background queue
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{

    // Tell the system that you want to start a background task
    UIBackgroundTaskIdentifier taskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        // Cleanup before system kills the app
    }];

    // Sleep the block for 5 seconds
    [NSThread sleepForTimeInterval:5.0];

    // Call the method if the app is backgrounded (and not just inactive)
    if (application.applicationState == UIApplicationStateBackground)
        [self performSelector:@selector(test)];  // Or, you could just call [self test]; here

    // Tell the system that the task has ended.
    if (taskID != UIBackgroundTaskInvalid) {
        [[UIApplication sharedApplication] endBackgroundTask:taskID];
    }

});

【讨论】:

  • 文尼,帮帮忙!谢谢!
猜你喜欢
  • 1970-01-01
  • 2023-03-14
  • 2016-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-20
  • 2013-06-14
相关资源
最近更新 更多