iOS 和 Android 中的后台运行问题

时间:2022-12-31 09:14:59

后台机制的不同,算是iOS 和 Android的一大区别了,最近发布的iOS7又对后台处理做了一定的更改,找时间总结一下编码上的区别,先做个记录。

先看看iOS的把,首先需要仔细阅读一下Apple的官方文档 iOS App Programming Guide中的App States and Multitasking,其中的Background Execution and Multitasking部分要仔细阅读。

ios的程序有5种状态,not running,inactive, active, background,suspended.其中,符合“标准的后台运行”的,只有background这个状态。但是这个状态的时间是有限制的,ios6最长约10分钟,ios7最长约3分钟。在这段时间内,即使系统锁屏也不会对程序的执行产生影响。To request background execution time, call the beginBackgroundTaskWithName:expirationHandler: method of the UIApplication class.  这种task也被称作Finite-Length Background Task。

与Finite-Length Background Task 相对的,有Long-Running Background Tasks,这种task在表现上就是在后台运行的任务,但是,它的类型是有限制的,并且需要在xcode中注册,导入对应的framework。现在支持的类型有,听音频,录音,获得地理位置,网络电话,下载数据,获得传感器数据。感觉上,下载数据可能是用处比较多。

Xcode mode

UIBackgroundModes value

Description

Audio

audio

The app plays audible content to the user or records audio while in the background. (This content includes streaming audio or video content using AirPlay.)

Location updates

location

The app keeps users informed of their location, even while it is running in the background.

Voice over IP

voip

The app provides the ability for the user to make phone calls using an Internet connection.

Newsstand downloads

newsstand-content

The app is a Newsstand app that downloads and processes magazine or newspaper content in the background.

External accessory communication

external-accessory

The app works with a hardware accessory that needs to deliver updates on a regular schedule through the External Accessory framework.

Bluetooth networking

bluetooth-central

The app works with a Bluetooth accessory that needs to deliver updates on a regular schedule through the Core Bluetooth framework.

Bluetooth data sharing

bluetooth-peripheral

The app supports Bluetooth communication in peripheral mode through the Core Bluetooth framework.

Using this mode requires user authorization; for more information, see “Best Practices for Maintaining User Privacy.”

Background fetch

fetch

The app regularly downloads and processes small amounts of content from the network.

Remote notifications

remote-notification

The app’s response to a push notification includes optionally downloading content related to the notification. The purpose of downloading the content in the background is to incorporate it and be able to present it immediately when the user responds to the push notification.

根据不同的类型,后台的表现也不太一致。

1.Background fetch

采用Background fetch 类型时,系统会根据情况自动去调用- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler 方法,但是经过我用ipad测试,我发现这个方法调用的频率并不高,如果你想利用这个函数做一些频率高的检测工作,恐怕是不行了!以下是我测试一小时的数据(我的设置 [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];)

-- ::02.353 BackgroundTest[:60b] performFetchWithCompletionHandler
-- ::49.829 BackgroundTest[:60b] performFetchWithCompletionHandler
-- ::48.132 BackgroundTest[:60b] performFetchWithCompletionHandler
-- ::01.594 BackgroundTest[:60b] performFetchWithCompletionHandler

从22.38开始,我开始使用了其他的应用,系统一直保持运行,结果到了11.05我不再使用,快待机前,系统才掉用了performFetchWithCompletionHandler函数,间隔几乎是30分钟!如果你一直运行占用系统资源较多的程序,我怀疑这个方法会不会一直不被调用。所以正如官方说明的,这个方法是用来下载一些小的数据的,目的是提前下载好资料,不需要用户等待数据下载,提高用户体验。如果你的程序按照这个标准去利用这个方法,那么当performFetchWithCompletionHandler不被系统调用时,也不会产生任何问题----用户只是在进入程序时需要多等待一会儿,去下载数据。然而,如果你打算利用这个方法去做一些特别的后台操作,就很有可能因为performFetchWithCompletionHandler不被系统及时调用而产生各种bug。

2 Remote notifications

ios7 前,一个远程的通知不具备在后台调用代码的功能。ios7中加入了这个功能。When this value is present and a push notification arrives on a device, the system sends the notification to your app (launching it if needed) and gives it a few moments to process the notification before displaying anything to the user. You can use those few moments to download content related to the push notification and be ready to display it to the user.

另外需要注意下列问题!

As soon as you finish processing the notification, you must call the block in the handler parameter or your app will be terminated. Your app has up to  seconds of wall-clock time to process the notification and call the specified completion handler block. In practice, you should call the handler block as soon as you are done processing the notification. The system tracks the elapsed time, power usage, and data costs for your app’s background downloads. Apps that use significant amounts of power when processing remote notifications may not always be woken up early to process future notifications.

从这里看出我们应该尽快调用completionHandler,防止系统组织程序的后台运行。但是如果我们故意立即调用completionHandler,而事实上还继续执行代码会怎么样呢?

//请参阅下面的文档,文档原地址为

http://docs.jpush.cn/display/dev/iOS+7+Background+Remote+Notification

为了防止原链接失效,拷贝如下:



简介

本次iOS 7在推送方面最大的变化就是允许,应用收到通知后在后台(background)状态下运行一段代码,可用于从服务器获取内容更新。功能使用场景:(多媒体)聊天,Email更新,基于通知的订阅内容同步等功能,提升了终端用户的体验。

Remote Notifications 与之前版本的对比可以参考下面两张 Apple 官方的图片便可一目了然。

iOS 和 Android 中的后台运行问题

iOS 和 Android 中的后台运行问题

如果只携带content-available: 1 不携带任何badge,sound 和消息内容等参数,则可以不打扰用户的情况下进行内容更新等操作即为“Silent Remote Notifications”。

iOS 和 Android 中的后台运行问题

客户端设置

开启Remote notifications

需要在Xcode 中修改应用的 Capabilities 开启Remote notifications,请参考下图:

iOS 和 Android 中的后台运行问题

修改通知处理函数

当注册了Backgroud Modes -> Remote notifications 后,notification 处理函数一律切换到下面函数,后台推送代码也在此函数中调用。

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler;

服务端推送设置

推送消息携带 content-available: 1 是Background 运行的必须参数,如果不携带此字段则与iOS7 之前版本的普通推送一样。

(这里是重中之重!以前测试时,就是因为没有设定这个参数,导致无法出发后台执行效果,还以为是ios的bug!)

使用Web Portal 推送

在“可选设置内”选择对应的参数。

iOS 和 Android 中的后台运行问题

使用 API 推送

只需在 Push API v2 的 n_extras->ios 内附加content-available":1 字段即可

{"n_content":"通知内容", "n_extras":{"ios":{"content-available":1,"badge":88, "sound":"happy"}, "user_param_1":"value1", "user_param_2":"value2"}}

限制与注意

  • “Silent Remote Notifications”是在 Apple 的限制下有一定的频率控制,但具体频率不详。所以并不是所有的 “Silent Remote Notifications” 都能按照预期到达客户端触发函数。
  • “Background”下提供给应用的运行时间窗是有限制的,如果需要下载较大的文件请参考 Apple 的 NSURLSession 的介绍。
  • “Background  Remote Notification”  的前提是要求客户端处于Background 或 Suspended 状态,如果用户通过 App Switcher 将应用从后台 Kill 掉应用将不会唤醒应用处理 background 代码。

更详细的说明资料请查阅 Apple 官方的 iOS 开发文档。



3 .newsstand downloads


再看看Android,Android中的Service就可以实现真正的后台运行。A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application.

什么时候一个service会被强制结束呢?The Android system will force-stop a service only when memory is low and it must recover system resources for the activity that has user focus. If the service is bound to an activity that has user focus, then it's less likely to be killed, and if the service is declared to run in the foreground (discussed later), then it will almost never be killed.

iOS 和 Android 中的后台运行问题的更多相关文章

  1. 【iOS系列】-程序开启后台运行

    [iOS系列]-程序开启后台运行 iOS程序是伪后台的运行,可是有时候我们需要让其在后台也要进行一些操作,我们可以让其伪装成音乐的APP,这样就可以让程序后台进行相关操作了,具体做法如下: 1:在Ap ...

  2. Android中获取正在运行的服务-------ActivityManager.RunningServiceInfo的使用

    关于PackageManager和ActivityManager的使用 ,自己也写了一些DEMO 了,基本上写的线路参考了Settings模块下的 应用程序,大家如果真正的有所兴趣,建议大家看看源码, ...

  3. Android 实现Activity后台运行

    有时需要让activity在后台运行,具体实现方法如下: 在AndroidManifest.xml中,activity属性中增加: android:theme="@style/Backgro ...

  4. iOS 和Android中的基本日期处理

    提到日期处理,主要有2个参数,一个是所在的时区,一个是所用的日历方法. 主要涉及2大类问题,一类是日期类型和字符串之间的转化,另一类是日期的计算问题.ios和android都提供了相应的类来处理问题. ...

  5. iOS 和Android中的正则表达式简单使用

    ios 中需要使用NSRegularExpression类,NSTextCheckingResult类. 下面给出最基本的实现代码 NSRegularExpression *regex = [NSRe ...

  6. iOS 和 Android 中的Alert

    iOS 和 Android中都有alert这种提示框,下面简单介绍下. ios中的alert叫做UIAlertView,共有4种样式,由于在ios7上,自定义alertview不太好用,所以也就这4种 ...

  7. Android中获取正在运行的应用程序-----ActivityManager.RunningAppProcessInfo类详解

    今天继续讲解关于ActivityManager的使用,通过前面一节的学习,我们学会了如何利用ActivityManager获取系统里 正在运行的进程.本文要讲解的知识点是利用这些进程信息获取系统里正在 ...

  8. Android中使用IntentService运行后台任务

    IntentService提供了一种在后台线程中运行任务的方式,适合处理运行时间较长的后台任务. 长处: (1)IntentService执行在单独的线程中.不会堵塞UI线程 (2)IntentSer ...

  9. Android长时间后台运行Service

         项目需要在后台获取GPS经纬度.当用户对手机有一段时间没有操作后,屏幕(Screen)将从高亮(Bright)变为暗淡(Dim),如果再过段时间没操作, 屏幕(Screen)将又由暗淡(Di ...

随机推荐

  1. 谈谈JavaScript MVC模式

    第一个是:没有使用mvc模式的: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "h ...

  2. jquery实现全选、反选、不选

    <!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8&quo ...

  3. Java-马士兵设计模式学习笔记-责任链模式-处理数据

    一.目标 数据提交前做各种处理 二.代码 1.MsgProcessor.java public class MsgProcessor { private List<Filter> filt ...

  4. 读书笔记-《Training Products of Experts by Minimizing Contrastive Divergence》

    Training Products of Experts by Minimizing Contrastive Divergence(以下简称 PoE)是 DBN 和深度学习理论的 肇始之篇,最近在爬梳 ...

  5. Python之子进程subprocess模块

    http://www.cnblogs.com/vamei/archive/2012/09/23/2698014.html http://blog.csdn.net/jgood/article/deta ...

  6. 使用git将本地代码传到github

    方法可能有些小小的差别,但是最终的结果都是一样的 在github上新建代码仓库 确定之后会显示一个仓库的url,复制下来 在本地找一个作为本地仓库的文件夹右键Git Bash Here打开git 把g ...

  7. 2星&vert;《IT真相》:日本咨询师面对美国云服务的发展,对日本IT业哀其不争

    IT真相-打通IT与商务的通路 I 作者是日本管理咨询师,对日本的IT和金融业了解比较多.书的内容是:作者看到美国的云服务发展壮大,日本IT业没能抓住机会,对日本IT业做了一些批评,比如不思进取,不了 ...

  8. Windows使用tail命令跟踪日志

    我们知道如果是Unix/Linux环境可以直接使用 tail -f xxx.log即可. 但是Windows并没有自带这个命令,不过从网上可以找到tail.zip 实测可以将其解压放在C:\Windo ...

  9. 汉明码(Hamming)编码与纠错原理

    一 汉明码的编解码说明 (一)编码 Hamming(12,8) N=12,表示编码后的比特长度 K=8,待编码数据的比特长度 R=N-K=4,校验位的比特长度 D=3 汉明距离:相邻行之间不同比特数据 ...

  10. NMS和soft-nms算法

    非极大值抑制算法(nms) 1. 算法原理 非极大值抑制算法(Non-maximum suppression, NMS)的本质是搜索局部极大值,抑制非极大值元素. 2. 3邻域情况下NMS的实现 3邻 ...