在后台运行应用程序超过10分钟

时间:2021-12-08 05:09:05

I am trying to keep the iOS app in active state for more than 10 mins when it enters in background state.

我试图让iOS应用程序进入后台状态时保持活动状态超过10分钟。

How can I implement this.

我该如何实现呢。

7 个解决方案

#1


55  

See "Background Execution" section of the iPhoneAppProgrammingGuide. In short, your app must be one of these types:

请参阅iPhoneAppProgrammingGuide的“后台执行”部分。简而言之,您的应用必须是以下类型之一:

  • Apps that play audible content to the user while in the background, such as a music player app
  • 在后台播放用户可听内容的应用,例如音乐播放器应用
  • Apps that keep users informed of their location at all times, such as a navigation app
  • 可让用户随时了解其位置的应用,例如导航应用
  • Apps that support Voice over Internet Protocol (VoIP)
  • 支持互联网协议语音(VoIP)的应用
  • Newsstand apps that need to download and process new content
  • 需要下载和处理新内容的报亭应用程序
  • Apps that receive regular updates from external accessories
  • 从外部配件接收定期更新的应用程序

And you must add to the Info.plist as follows: Add the UIBackgroundModes key to your Info.plist file and set its value to an array containing one or more of the following strings:

您必须按如下方式添加到Info.plist:将UIBackgroundModes键添加到Info.plist文件,并将其值设置为包含以下一个或多个字符串的数组:

  • audio—The app plays audible content to the user while in the background. (This content includes streaming audio or video content using AirPlay.)
  • audio-该应用程序在后台播放可听内容给用户。 (此内容包括使用AirPlay播放音频或视频内容。)
  • location—The app keeps users informed of their location, even while it is running in the background.
  • location - 该应用程序可让用户随时了解其位置,即使它在后台运行也是如此。
  • voip—The app provides the ability for the user to make phone calls using an Internet connection.
  • voip-该应用程序使用户能够使用Internet连接拨打电话。
  • newsstand-content—The app is aNewsstand app that downloads and processesmagazine or newspaper content in the background.
  • 报亭 - 内容 - 该应用程序是一个新闻台应用程序,可在后台下载和处理杂志或报纸内容。
  • external-accessory—The app works with a hardware accessory that needs to deliver updates on a regular schedule through the External Accessory framework.
  • external-accessory-该应用程序与硬件附件配合使用,需要通过外部附件框架定期提供更新。
  • bluetooth-central—The app works with a Bluetooth accessory that needs to deliver updates on a regular schedule through the CoreBluetooth framework
  • bluetooth-central-该应用程序与蓝牙配件配合使用,需要通过CoreBluetooth框架定期提供更新

Note that part of the review process will be checking to make sure that your app does what it says it's doing with regard to background processing.

请注意,审核流程的一部分将进行检查,以确保您的应用能够执行其在后台处理方面所做的工作。

#2


20  

Here's what I've done using beginBackgroundTaskWithExpirationHandler.

这是我使用beginBackgroundTaskWithExpirationHandler完成的。

  • Write a method that starts a background task.
  • 编写一个启动后台任务的方法。
  • Inside that background task, run a NSTimer with a scheduled (non repeating) time that is under 10 minutes. For the purposes of my situation I was using 5 minutes.
  • 在该后台任务中,运行NSTimer,其计划(非重复)时间不超过10分钟。出于我的情况,我使用了5分钟。
  • Once the NStimer's selector fires, end the background task and then instantly call the method that you wrote earlier to start off another background task.
  • 一旦NStimer的选择器触发,结束后台任务,然后立即调用您之前编写的方法开始另一个后台任务。
  • If you want to schedule methods to run at specific times, you will have to check for them in the background task.
  • 如果要安排在特定时间运行的方法,则必须在后台任务中检查它们。

This solution isn't really ideal and is still power hungry but will do what you want.

这个解决方案并不是很理想,但仍然很耗电,但会做你想要的。

Edit: Since iOS7, I suggest you read this excellent post.

编辑:自iOS7以来,我建议你阅读这篇优秀的帖子。

#3


2  

Only certain types of apps are allowed to run in the background. See the "Implementing Long-Running Background Tasks" section of this guide.

只允许某些类型的应用在后台运行。请参阅本指南的“实现长时间运行的后台任务”部分。

If you aren't requesting permissions to do background processing you can use UIApplication's beginBackgroundTaskWithExpirationHandler but you cannot get extra time.

如果您没有请求权限进行后台处理,您可以使用UIApplication的beginBackgroundTaskWithExpirationHandler,但是您无法获得额外的时间。

#4


2  

This code makes your iOS app run indefinitely in the background. Copy and paste the below methods into a singleton / manager which handles the tasks you need to perform in the background.

此代码使您的iOS应用程序在后台无限期运行。将以下方法复制并粘贴到单件/管理器中,该单件/管理器处理您需要在后台执行的任务。

// @interface

// Declare Private property
@property (nonatomic) UIBackgroundTaskIdentifier backgroundTask;

//@end
// ...

// Copy into
//@implementation 

- (void)setupBackgrounding {
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appBackgrounding:)
                                                 name: UIApplicationDidEnterBackgroundNotification
                                               object: nil];
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appForegrounding:)
                                                 name: UIApplicationWillEnterForegroundNotification
                                               object: nil];
}

- (void)appBackgrounding: (NSNotification *)notification {
    [self keepAlive];
}

- (void) keepAlive {
    self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
        self.backgroundTask = UIBackgroundTaskInvalid;
        [self keepAlive];
    }];
}

- (void)appForegrounding: (NSNotification *)notification {
    if (self.backgroundTask != UIBackgroundTaskInvalid) {
        [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
        self.backgroundTask = UIBackgroundTaskInvalid;
    }
}

#5


0  

You can't. Unless your app uses audio, voip or gps. What you can do is notify the user (via local notifications) that the time is almost up and ask him to open/close the app.

你不能。除非您的应用使用音频,voip或gps。您可以做的是通知用户(通过本地通知)时间快到了并要求他打开/关闭应用程序。

Also if you just need to notify the user, you can use push notifications.

此外,如果您只需要通知用户,则可以使用推送通知。

#6


0  

https://github.com/yarodevuci/backgroundTask Check my code here I am using audio player that plays blank wav file Works perfectly on IOS 8 Battery usage around 10% in 24 hour period How to use:

https://github.com/yarodevuci/backgroundTask在这里查看我的代码我正在使用播放空白wav文件的音频播放器在IOS 8上完美工作24小时内电池使用率约为10%如何使用:

var backgroundTask = BackgroundTask()
backgroundTask.startBackgroundTask() //Starts playing blank audio file. You can run NSTimer() or whatever you need and it will continue executing in the background.

backgroundTask.stopBackgroundTask() //Stops the task

Warning: Apple will reject this if you try to submit it!

警告:如果您尝试提交,Apple会拒绝此操作!

#7


0  

If your App type is not one of VOIP/Audio/Location....(check Background Modes),

如果您的应用程序类型不是VOIP /音频/位置....(检查后台模式),

or you don't want to specify your App as a background App, you can implement beginBackgroundTaskWithName:expirationHandler or beginBackgroundTaskWithExpirationHandler to ask for more time to run your process in background. You can find the detailed description here

或者您不希望将应用程序指定为后台应用程序,您可以实现beginBackgroundTaskWithName:expirationHandler或beginBackgroundTaskWithExpirationHandler以请求更多时间在后台运行您的进程。您可以在此处找到详细说明

Apps moving to the background are expected to put themselves into a quiescent state as quickly as possible so that they can be suspended by the system. If your app is in the middle of a task and needs a little extra time to complete that task, it can call the beginBackgroundTaskWithName:expirationHandler: or beginBackgroundTaskWithExpirationHandler: method of the UIApplication object to request some additional execution time. Calling either of these methods delays the suspension of your app temporarily, giving it a little extra time to finish its work. Upon completion of that work, your app must call the endBackgroundTask: method to let the system know that it is finished and can be suspended.

移动到后台的应用程序应尽快进入静止状态,以便系统可以暂停它们。如果您的应用程序处于任务中间并且需要一些额外的时间来完成该任务,它可以调用beginBackgroundTaskWithName:expirationHandler:或beginBackgroundTaskWithExpirationHandler:UIApplication对象的方法来请求一些额外的执行时间。调用这些方法中的任何一种都会暂时延迟暂停您的应用程序,从而为其完成工作留出一点额外时间。完成该工作后,您的应用必须调用endBackgroundTask:方法让系统知道它已完成并可以暂停。

Each call to the beginBackgroundTaskWithName:expirationHandler: or beginBackgroundTaskWithExpirationHandler: method generates a unique token to associate with the corresponding task. When your app completes a task, it must call the endBackgroundTask: method with the corresponding token to let the system know that the task is complete. Failure to call the endBackgroundTask: method for a background task will result in the termination of your app. If you provided an expiration handler when starting the task, the system calls that handler and gives you one last chance to end the task and avoid termination.

每次调用beginBackgroundTaskWithName:expirationHandler:或beginBackgroundTaskWithExpirationHandler:方法都会生成一个唯一的令牌以与相应的任务相关联。当您的应用程序完成任务时,它必须使用相应的令牌调用endBackgroundTask:方法,以让系统知道任务已完成。未能为后台任务调用endBackgroundTask:方法将导致应用程序终止。如果在启动任务时提供了过期处理程序,系统将调用该处理程序并为您提供最后一次结束任务并避免终止的机会。

#1


55  

See "Background Execution" section of the iPhoneAppProgrammingGuide. In short, your app must be one of these types:

请参阅iPhoneAppProgrammingGuide的“后台执行”部分。简而言之,您的应用必须是以下类型之一:

  • Apps that play audible content to the user while in the background, such as a music player app
  • 在后台播放用户可听内容的应用,例如音乐播放器应用
  • Apps that keep users informed of their location at all times, such as a navigation app
  • 可让用户随时了解其位置的应用,例如导航应用
  • Apps that support Voice over Internet Protocol (VoIP)
  • 支持互联网协议语音(VoIP)的应用
  • Newsstand apps that need to download and process new content
  • 需要下载和处理新内容的报亭应用程序
  • Apps that receive regular updates from external accessories
  • 从外部配件接收定期更新的应用程序

And you must add to the Info.plist as follows: Add the UIBackgroundModes key to your Info.plist file and set its value to an array containing one or more of the following strings:

您必须按如下方式添加到Info.plist:将UIBackgroundModes键添加到Info.plist文件,并将其值设置为包含以下一个或多个字符串的数组:

  • audio—The app plays audible content to the user while in the background. (This content includes streaming audio or video content using AirPlay.)
  • audio-该应用程序在后台播放可听内容给用户。 (此内容包括使用AirPlay播放音频或视频内容。)
  • location—The app keeps users informed of their location, even while it is running in the background.
  • location - 该应用程序可让用户随时了解其位置,即使它在后台运行也是如此。
  • voip—The app provides the ability for the user to make phone calls using an Internet connection.
  • voip-该应用程序使用户能够使用Internet连接拨打电话。
  • newsstand-content—The app is aNewsstand app that downloads and processesmagazine or newspaper content in the background.
  • 报亭 - 内容 - 该应用程序是一个新闻台应用程序,可在后台下载和处理杂志或报纸内容。
  • external-accessory—The app works with a hardware accessory that needs to deliver updates on a regular schedule through the External Accessory framework.
  • external-accessory-该应用程序与硬件附件配合使用,需要通过外部附件框架定期提供更新。
  • bluetooth-central—The app works with a Bluetooth accessory that needs to deliver updates on a regular schedule through the CoreBluetooth framework
  • bluetooth-central-该应用程序与蓝牙配件配合使用,需要通过CoreBluetooth框架定期提供更新

Note that part of the review process will be checking to make sure that your app does what it says it's doing with regard to background processing.

请注意,审核流程的一部分将进行检查,以确保您的应用能够执行其在后台处理方面所做的工作。

#2


20  

Here's what I've done using beginBackgroundTaskWithExpirationHandler.

这是我使用beginBackgroundTaskWithExpirationHandler完成的。

  • Write a method that starts a background task.
  • 编写一个启动后台任务的方法。
  • Inside that background task, run a NSTimer with a scheduled (non repeating) time that is under 10 minutes. For the purposes of my situation I was using 5 minutes.
  • 在该后台任务中,运行NSTimer,其计划(非重复)时间不超过10分钟。出于我的情况,我使用了5分钟。
  • Once the NStimer's selector fires, end the background task and then instantly call the method that you wrote earlier to start off another background task.
  • 一旦NStimer的选择器触发,结束后台任务,然后立即调用您之前编写的方法开始另一个后台任务。
  • If you want to schedule methods to run at specific times, you will have to check for them in the background task.
  • 如果要安排在特定时间运行的方法,则必须在后台任务中检查它们。

This solution isn't really ideal and is still power hungry but will do what you want.

这个解决方案并不是很理想,但仍然很耗电,但会做你想要的。

Edit: Since iOS7, I suggest you read this excellent post.

编辑:自iOS7以来,我建议你阅读这篇优秀的帖子。

#3


2  

Only certain types of apps are allowed to run in the background. See the "Implementing Long-Running Background Tasks" section of this guide.

只允许某些类型的应用在后台运行。请参阅本指南的“实现长时间运行的后台任务”部分。

If you aren't requesting permissions to do background processing you can use UIApplication's beginBackgroundTaskWithExpirationHandler but you cannot get extra time.

如果您没有请求权限进行后台处理,您可以使用UIApplication的beginBackgroundTaskWithExpirationHandler,但是您无法获得额外的时间。

#4


2  

This code makes your iOS app run indefinitely in the background. Copy and paste the below methods into a singleton / manager which handles the tasks you need to perform in the background.

此代码使您的iOS应用程序在后台无限期运行。将以下方法复制并粘贴到单件/管理器中,该单件/管理器处理您需要在后台执行的任务。

// @interface

// Declare Private property
@property (nonatomic) UIBackgroundTaskIdentifier backgroundTask;

//@end
// ...

// Copy into
//@implementation 

- (void)setupBackgrounding {
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appBackgrounding:)
                                                 name: UIApplicationDidEnterBackgroundNotification
                                               object: nil];
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appForegrounding:)
                                                 name: UIApplicationWillEnterForegroundNotification
                                               object: nil];
}

- (void)appBackgrounding: (NSNotification *)notification {
    [self keepAlive];
}

- (void) keepAlive {
    self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
        self.backgroundTask = UIBackgroundTaskInvalid;
        [self keepAlive];
    }];
}

- (void)appForegrounding: (NSNotification *)notification {
    if (self.backgroundTask != UIBackgroundTaskInvalid) {
        [[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
        self.backgroundTask = UIBackgroundTaskInvalid;
    }
}

#5


0  

You can't. Unless your app uses audio, voip or gps. What you can do is notify the user (via local notifications) that the time is almost up and ask him to open/close the app.

你不能。除非您的应用使用音频,voip或gps。您可以做的是通知用户(通过本地通知)时间快到了并要求他打开/关闭应用程序。

Also if you just need to notify the user, you can use push notifications.

此外,如果您只需要通知用户,则可以使用推送通知。

#6


0  

https://github.com/yarodevuci/backgroundTask Check my code here I am using audio player that plays blank wav file Works perfectly on IOS 8 Battery usage around 10% in 24 hour period How to use:

https://github.com/yarodevuci/backgroundTask在这里查看我的代码我正在使用播放空白wav文件的音频播放器在IOS 8上完美工作24小时内电池使用率约为10%如何使用:

var backgroundTask = BackgroundTask()
backgroundTask.startBackgroundTask() //Starts playing blank audio file. You can run NSTimer() or whatever you need and it will continue executing in the background.

backgroundTask.stopBackgroundTask() //Stops the task

Warning: Apple will reject this if you try to submit it!

警告:如果您尝试提交,Apple会拒绝此操作!

#7


0  

If your App type is not one of VOIP/Audio/Location....(check Background Modes),

如果您的应用程序类型不是VOIP /音频/位置....(检查后台模式),

or you don't want to specify your App as a background App, you can implement beginBackgroundTaskWithName:expirationHandler or beginBackgroundTaskWithExpirationHandler to ask for more time to run your process in background. You can find the detailed description here

或者您不希望将应用程序指定为后台应用程序,您可以实现beginBackgroundTaskWithName:expirationHandler或beginBackgroundTaskWithExpirationHandler以请求更多时间在后台运行您的进程。您可以在此处找到详细说明

Apps moving to the background are expected to put themselves into a quiescent state as quickly as possible so that they can be suspended by the system. If your app is in the middle of a task and needs a little extra time to complete that task, it can call the beginBackgroundTaskWithName:expirationHandler: or beginBackgroundTaskWithExpirationHandler: method of the UIApplication object to request some additional execution time. Calling either of these methods delays the suspension of your app temporarily, giving it a little extra time to finish its work. Upon completion of that work, your app must call the endBackgroundTask: method to let the system know that it is finished and can be suspended.

移动到后台的应用程序应尽快进入静止状态,以便系统可以暂停它们。如果您的应用程序处于任务中间并且需要一些额外的时间来完成该任务,它可以调用beginBackgroundTaskWithName:expirationHandler:或beginBackgroundTaskWithExpirationHandler:UIApplication对象的方法来请求一些额外的执行时间。调用这些方法中的任何一种都会暂时延迟暂停您的应用程序,从而为其完成工作留出一点额外时间。完成该工作后,您的应用必须调用endBackgroundTask:方法让系统知道它已完成并可以暂停。

Each call to the beginBackgroundTaskWithName:expirationHandler: or beginBackgroundTaskWithExpirationHandler: method generates a unique token to associate with the corresponding task. When your app completes a task, it must call the endBackgroundTask: method with the corresponding token to let the system know that the task is complete. Failure to call the endBackgroundTask: method for a background task will result in the termination of your app. If you provided an expiration handler when starting the task, the system calls that handler and gives you one last chance to end the task and avoid termination.

每次调用beginBackgroundTaskWithName:expirationHandler:或beginBackgroundTaskWithExpirationHandler:方法都会生成一个唯一的令牌以与相应的任务相关联。当您的应用程序完成任务时,它必须使用相应的令牌调用endBackgroundTask:方法,以让系统知道任务已完成。未能为后台任务调用endBackgroundTask:方法将导致应用程序终止。如果在启动任务时提供了过期处理程序,系统将调用该处理程序并为您提供最后一次结束任务并避免终止的机会。