IOS高级开发~开机启动&无限后台运行&监听进程

一般来说, IOS很少给App后台运行的权限. 仅有的方式就是 VoIP. IOS少有的为VoIP应用提供了后台socket连接,定期唤醒并且随开机启动的权限.而这些就是IOS上实现VoIP App的关键. 苹果官方文档对于的描述就短短的一页(点击这里),很多细节没有提及. 这篇微博通过具体实现和查阅资料,补充了这些细节.并且列举出了在实现过程中可能遇到的问题, 作为参考.


  • 博客: http://www.cnblogs.com/jhzhu
  • 邮箱: jhzhuustc@gmail.com
  • 作者: 知明所以
  • 时间: 2013-11-10

官方文档描述如是:

PS:此节纯用来占座.如果你你E文不好或者想直接切入正题, 请看下一标题.

There are several requirements for implementing a VoIP app:

  1. Add the UIBackgroundModes key to your app’s Info.plist file. Set the value of this key to an array that includes the voip string.
  2. Configure one of the app’s sockets for VoIP usage.
  3. Before moving to the background, call the setKeepAliveTimeout:handler: method to install a handler to be executed periodically. Your app can use this handler to maintain its service connection.
  4. Configure your audio session to handle transitions to and from active use.
  5. To ensure a better user experience on iPhone, use the Core Telephony framework to adjust your behavior in relation to cell-based phone calls; see Core Telephony Framework Reference.
  6. To ensure good performance for your VoIP app, use the System Configuration framework to detect network changes and allow your app to sleep as much as possible.

我的翻译:

关于IOS为VoIP应用提供的特殊权限和实现方法,我的描述如下. 我尽可能的涉及到voip实现的各种细节, 这样你能对这个运作机制有一个更好的理解,我觉得这远比单单贴几行代码有意义. 因为一个开发者在实际实现过程中遇到的千难险阻很少会体现在最终代码上, 就如你永远不知道台上的角儿在台下的挫折.

  1. IOS允许App的一个Socket在App切换到后台后仍然保持连接. 这样,当有通话请求的时候,App能及时处理. 这个socket需要在应用第一次启动的时候创建, 并标记为"此socket用于VoIP服务". 这样当App切换到后台的时候,IOS会接管这个标记为"用于VoIP服务"的socket. 这个socket的响应函数(比如,一个delegate,或者是个block)会正常的响应, 就像App还在前台一样.
  2. 10s魔咒. 当socket有任何数据从服务端传来, 你在app里为socket写的响应函数都会做处理.但是, 你只有最多10s的时间来干你想干的事情. 也就意味着你在响应函数里新建一个大于10s的timer是没有意义的. 并且IOS并不保证给你足够10s的时间,视系统情况而定.
  3. socket的响应函数里, 你能通过NSLocalNotification来通知用户"电话来了". 除此之外, 你没法做其他任何视觉上的动作来提醒用户, 因为你的app还处于某个不知道的次元, 甚至连window都还没创建.
  4. 你永远也没有办法知道或者决定NSLocalNotification的样式是banner还是alert. 你也许钟爱后者, 但是决定权在用户手里.
  5. 允许在后台定期执行一段代码. 你可以设定一个大于等于10分钟的时间t, 和一个定期执行的handler, IOS系统会在每次经过t时间的时候调用一次这个handler. 但是IOS不保证这个handler会准时运行, 只保证在时间t范围内的某个点会执行一次.
  6. 我们通常用楼上的handler处理socket的断线重连操作. 因为网络不稳定, 或者用户开启飞行模式等原因, 我们用于voip服务的socket会断开连接. 在这个handler里,如果发现连接断开,我们只需要跟条目1一样的创建socket,设置一样的socket响应函数,一切又会恢复正常.
  7. 不建议这个handler做太多事情, 因为它也有10s魔咒.(据不完全统计,苹果所有的后台处理都有这个10s限制. 不保证绝对正确哈, 仅供参考)
  8. 自启服务. 当IOS重新启动, 或者你的app因为其他原因退出时, IOS会马上启动你注册为voip的app, 你可以很迅速的恢复socket连接. 但是, 从底部多任务栏中手动关闭应用除外.更"code"的说明是:当程序退出的exitcode != 0,IOS会重启你的app.经试验发现,从底部多任务栏关闭的时候,程序的exitcode == 0.
  9. 如果你亲爱的用户是一个典型的"app终结者",那么你还剩最后一条路来通知来电提醒:NSRemoteNotification. 你也许会被NSRemoteNotification的可靠性和实时性折腾的抓狂, 但是, 谁让你选了IOS? 你享受了封闭带来的传世体验, 也得承受封闭的限制.
  10. 当条目8描述的情况发生之后,app的application:didFinishLaunchingWithOptions:会被调用. 但是,请时刻提醒自己我们的app仍然处于后台. 我们以前总在这里创建window创建rootController, 但现在不必了. 现在我们需要的就是把可爱的socket连上, 像在条目1里一样,让一切回归正常(我不去写歌词真浪费了^_^).
  11. application:didFinishLaunchingWithOptions:里你能通过[application applicationState] == UIApplicationStateBackground来判断是正常启动应用还是系统自动启动, 然后决定该创建window还是创建voip的socket.

 

非越狱情况下实现:

开机启动:App安装到IOS设备设备之后,无论App是否开启过,只要IOS设备重启,App就会随之启动;

无限后台运行:应用进入后台状态,可以无限后台运行,不被系统kill;

监听进程:可获IOS设备运行除系统外的App(包括正在运行和后台运行);

 

配置项目 plist文件

添加:

<key>UIBackgroundModes</key>

<array>

<string>voip</string>

</array>

 

功能类:ProccessHelper

 

[objc] view plaincopy
 
  1. #import <Foundation/Foundation.h>    
  2.     
  3. @interface ProccessHelper : NSObject    
  4.     
  5. + (NSArray *)runningProcesses;    
  6.     
  7. @end    
  8.   
  9. [cpp] view plaincopyprint?  
  10. #import "ProccessHelper.h"    
  11. //#include<objc/runtime.h>    
  12. #include <sys/sysctl.h>    
  13.     
  14. #include <stdbool.h>    
  15. #include <sys/types.h>    
  16. #include <unistd.h>    
  17. #include <sys/sysctl.h>    
  18.     
  19. @implementation ProccessHelper    
  20.     
  21. //You can determine if your app is being run under the debugger with the following code from    
  22. static bool AmIBeingDebugged(void)    
  23. // Returns true if the current process is being debugged (either    
  24. // running under the debugger or has a debugger attached post facto).    
  25. {    
  26.     int                 junk;    
  27.     int                 mib[4];    
  28.     struct kinfo_proc   info;    
  29.     size_t              size;    
  30.         
  31.     // Initialize the flags so that, if sysctl fails for some bizarre    
  32.     // reason, we get a predictable result.    
  33.         
  34.     info.kp_proc.p_flag = 0;    
  35.         
  36.     // Initialize mib, which tells sysctl the info we want, in this case    
  37.     // we're looking for information about a specific process ID.    
  38.         
  39.     mib[0] = CTL_KERN;    
  40.     mib[1] = KERN_PROC;    
  41.     mib[2] = KERN_PROC_PID;    
  42.     mib[3] = getpid();    
  43.         
  44.     // Call sysctl.    
  45.         
  46.     size = sizeof(info);    
  47.     junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);    
  48.     assert(junk == 0);    
  49.         
  50.     // We're being debugged if the P_TRACED flag is set.    
  51.         
  52.     return ( (info.kp_proc.p_flag & P_TRACED) != 0 );    
  53. }    
  54.     
  55. //返回所有正在运行的进程的 id,name,占用cpu,运行时间    
  56. //使用函数int   sysctl(int *, u_int, void *, size_t *, void *, size_t)    
  57. + (NSArray *)runningProcesses    
  58. {    
  59.     //指定名字参数,按照顺序第一个元素指定本请求定向到内核的哪个子系统,第二个及其后元素依次细化指定该系统的某个部分。    
  60.     //CTL_KERN,KERN_PROC,KERN_PROC_ALL 正在运行的所有进程    
  61.     int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL ,0};    
  62.         
  63.         
  64.     size_t miblen = 4;    
  65.     //值-结果参数:函数被调用时,size指向的值指定该缓冲区的大小;函数返回时,该值给出内核存放在该缓冲区中的数据量    
  66.     //如果这个缓冲不够大,函数就返回ENOMEM错误    
  67.     size_t size;    
  68.     //返回0,成功;返回-1,失败    
  69.     int st = sysctl(mib, miblen, NULL, &size, NULL, 0);    
  70.         
  71.     struct kinfo_proc * process = NULL;    
  72.     struct kinfo_proc * newprocess = NULL;    
  73.     do    
  74.     {    
  75.         size += size / 10;    
  76.         newprocess = realloc(process, size);    
  77.         if (!newprocess)    
  78.         {    
  79.             if (process)    
  80.             {    
  81.                 free(process);    
  82.                 process = NULL;    
  83.             }    
  84.             return nil;    
  85.         }    
  86.             
  87.         process = newprocess;    
  88.         st = sysctl(mib, miblen, process, &size, NULL, 0);    
  89.     } while (st == -1 && errno == ENOMEM);    
  90.         
  91.     if (st == 0)    
  92.     {    
  93.         if (size % sizeof(struct kinfo_proc) == 0)    
  94.         {    
  95.             int nprocess = size / sizeof(struct kinfo_proc);    
  96.             if (nprocess)    
  97.             {    
  98.                 NSMutableArray * array = [[NSMutableArray alloc] init];    
  99.                 for (int i = nprocess - 1; i >= 0; i--)    
  100.                 {    
  101.                     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];    
  102.                     NSString * processID = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_pid];    
  103.                     NSString * processName = [[NSString alloc] initWithFormat:@"%s", process[i].kp_proc.p_comm];    
  104.                     NSString * proc_CPU = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_estcpu];    
  105.                     double t = [[NSDate date] timeIntervalSince1970] - process[i].kp_proc.p_un.__p_starttime.tv_sec;    
  106.                     NSString * proc_useTiem = [[NSString alloc] initWithFormat:@"%f",t];    
  107.                     NSString *startTime = [[NSString alloc] initWithFormat:@"%ld", process[i].kp_proc.p_un.__p_starttime.tv_sec];    
  108.                     NSString * status = [[NSString alloc] initWithFormat:@"%d",process[i].kp_proc.p_flag];    
  109.                         
  110.                     NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];    
  111.                     [dic setValue:processID forKey:@"ProcessID"];    
  112.                     [dic setValue:processName forKey:@"ProcessName"];    
  113.                     [dic setValue:proc_CPU forKey:@"ProcessCPU"];    
  114.                     [dic setValue:proc_useTiem forKey:@"ProcessUseTime"];    
  115.                     [dic setValue:proc_useTiem forKey:@"ProcessUseTime"];    
  116.                     [dic setValue:startTime forKey:@"startTime"];    
  117.                         
  118.                     // 18432 is the currently running application    
  119.                     // 16384 is background    
  120.                     [dic setValue:status forKey:@"status"];    
  121.                         
  122.                     [processID release];    
  123.                     [processName release];    
  124.                     [proc_CPU release];    
  125.                     [proc_useTiem release];    
  126.                     [array addObject:dic];    
  127.                     [startTime release];    
  128.                     [status release];    
  129.                     [dic release];    
  130.                         
  131.                     [pool release];    
  132.                 }    
  133.                     
  134.                 free(process);    
  135.                 process = NULL;    
  136.                 //NSLog(@"array = %@",array);    
  137.                     
  138.                 return array;    
  139.             }    
  140.         }    
  141.     }    
  142.         
  143.     return nil;    
  144. }    
  145.     
  146. @end    

 

 

实现代码:

 

[objc] view plaincopy
 
  1. systemprocessArray = [[NSMutableArray arrayWithObjects:    
  2.                                 @"kernel_task",    
  3.                                 @"launchd",    
  4.                                 @"UserEventAgent",    
  5.                                 @"wifid",    
  6.                                 @"syslogd",    
  7.                                 @"powerd",    
  8.                                 @"lockdownd",    
  9.                                 @"mediaserverd",    
  10.                                 @"mediaremoted",    
  11.                                 @"mDNSResponder",    
  12.                                 @"locationd",    
  13.                                 @"imagent",    
  14.                                 @"iapd",    
  15.                                 @"fseventsd",    
  16.                                 @"fairplayd.N81",    
  17.                                 @"configd",    
  18.                                 @"apsd",    
  19.                                 @"aggregated",    
  20.                                 @"SpringBoard",    
  21.                                 @"CommCenterClassi",    
  22.                                 @"BTServer",    
  23.                                 @"notifyd",    
  24.                                 @"MobilePhone",    
  25.                                 @"ptpd",    
  26.                                 @"afcd",    
  27.                                 @"notification_pro",    
  28.                                 @"notification_pro",    
  29.                                 @"syslog_relay",    
  30.                                 @"notification_pro",    
  31.                                 @"springboardservi",    
  32.                                 @"atc",    
  33.                                 @"sandboxd",    
  34.                                 @"networkd",    
  35.                                 @"lsd",    
  36.                                 @"securityd",    
  37.                                 @"lockbot",    
  38.                                 @"installd",    
  39.                                 @"debugserver",    
  40.                                 @"amfid",    
  41.                                 @"AppleIDAuthAgent",    
  42.                                 @"BootLaunch",    
  43.                                 @"MobileMail",    
  44.                                 @"BlueTool",    
  45.                                 nil nil] retain];    

 

[objc] view plaincopy
 
    1. - (void)applicationDidEnterBackground:(UIApplication *)application    
    2. {    
    3.     while (1) {    
    4.         sleep(5);    
    5.         [self postMsg];    
    6.     }    
    7.         
    8. [cpp] view plaincopyprint?  
    9.     [[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:^{    
    10.         NSLog(@"KeepAlive");    
    11.     }];    
    12. }    
    13.     
    14. - (void)applicationWillResignActive:(UIApplication *)application    
    15. {    
    16. }    
    17. - (void)applicationWillEnterForeground:(UIApplication *)application    
    18. {    
    19. }    
    20. - (void)applicationDidBecomeActive:(UIApplication *)application    
    21. {    
    22. }    
    23. - (void)applicationWillTerminate:(UIApplication *)application    
    24. {    
    25. }    
    26.     
    27. #pragma mark -    
    28. #pragma mark - User Method    
    29.     
    30. - (void) postMsg    
    31. {    
    32.     //上传到服务器    
    33.     NSURL *url = [self getURL];    
    34.     NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];    
    35.     NSError *error = nil;    
    36.     NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];    
    37.         
    38.     if (error) {    
    39.         NSLog(@"error:%@", [error localizedDescription]);    
    40.     }    
    41.         
    42.     NSString *str = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];    
    43.     NSLog(@"%@",str);    
    44. }    
    45.     
    46. - (NSURL *) getURL    
    47. {    
    48.     UIDevice *device = [UIDevice currentDevice];    
    49.         
    50.     NSString* uuid = @"TESTUUID";    
    51.     NSString* manufacturer = @"apple";    
    52.     NSString* model = [device model];    
    53.     NSString* mobile = [device systemVersion];    
    54.         
    55.     NSString *msg = [NSString stringWithFormat:@"Msg:%@  Time:%@", [self processMsg], [self getTime]];    
    56.     CFShow(msg);    
    57.         
    58.     /  省略部分代码  /    
    59.         
    60.     NSString *urlStr = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    
    61.     NSURL *url = [NSURL URLWithString:urlStr];    
    62.         
    63.     return url;    
    64. }    
    65.     
    66. - (BOOL) checkSystemProccess:(NSString *) proName    
    67. {    
    68.     if ([systemprocessArray containsObject:proName]) {    
    69.         return YES;    
    70.     }    
    71.     return NO;    
    72. }    
    73.     
    74. - (BOOL) checkFirst:(NSString *) string    
    75. {    
    76.     NSString *str = [string substringToIndex:1];    
    77.     NSRange r = [@"ABCDEFGHIJKLMNOPQRSTUVWXWZ" rangeOfString:str];    
    78.         
    79.     if (r.length > 0) {    
    80.         return YES;    
    81.     }    
    82.     return NO;    
    83. }    
    84.     
    85. - (NSString *) processMsg    
    86. {    
    87.     NSArray *proMsg = [ProccessHelper runningProcesses];    
    88.     
    89.     if (proMsg == nil) {    
    90.         return nil;    
    91.     }    
    92.         
    93.     NSMutableArray *proState = [NSMutableArray array];    
    94.     for (NSDictionary *dic in proMsg) {    
    95.             
    96.         NSString *proName = [dic objectForKey:@"ProcessName"];    
    97.         if (![self checkSystemProccess:proName] && [self checkFirst:proName]) {    
    98.             NSString *proID = [dic objectForKey:@"ProcessID"];    
    99.             NSString *proStartTime = [dic objectForKey:@"startTime"];    
    100.                 
    101.             if ([[dic objectForKey:@"status"] isEqualToString:@"18432"]) {    
    102.                 NSString *msg = [NSString stringWithFormat:@"ProcessName:%@ - ProcessID:%@ - StartTime:%@ Running:YES", proName, proID, proStartTime];    
    103.                 [proState addObject:msg];    
    104.             } else {    
    105.                 NSString *msg = [NSString stringWithFormat:@"ProcessName:%@ - ProcessID:%@ - StartTime:%@ Running:NO", proName, proID, proStartTime];    
    106.                 [proState addObject:msg];    
    107.             }    
    108.         }    
    109.     }    
    110.         
    111.     NSString *msg = [proState componentsJoinedByString:@"______"];    
    112.     return msg;    
    113. }    
    114.     
    115. // 获取时间    
    116. - (NSString *) getTime    
    117. {    
    118.     NSDateFormatter *formatter =[[[NSDateFormatter alloc] init] autorelease];    
    119.     formatter.dateStyle = NSDateFormatterMediumStyle;    
    120.     formatter.timeStyle = NSDateFormatterMediumStyle;    
    121.     formatter.locale = [NSLocale currentLocale];    
    122.         
    123.     NSDate *date = [NSDate date];    
    124.         
    125.     [formatter setTimeStyle:NSDateFormatterMediumStyle];    
    126.     NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];    
    127.     NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];    
    128.     NSInteger unitFlags = NSYearCalendarUnit |    
    129.     NSMonthCalendarUnit |    
    130.     NSDayCalendarUnit |    
    131.     NSWeekdayCalendarUnit |    
    132.     NSHourCalendarUnit |    
    133.     NSMinuteCalendarUnit |    
    134.     NSSecondCalendarUnit;    
    135.     comps = [calendar components:unitFlags fromDate:date];    
    136.     int year = [comps year];    
    137.     int month = [comps month];    
    138.     int day = [comps day];    
    139.     int hour = [comps hour];    
    140.     int min = [comps minute];    
    141.     int sec = [comps second];    
    142.         
    143.     NSString *time = [NSString stringWithFormat:@"%d-%d-%d %d:%d:%d", year, month, day, hour, min, sec];    
    144.        
    145.     return time;    
    146. }    
    147.     
    148. @end    
posted @ 2014-11-19 16:35  aba-solution  阅读(2024)  评论(0编辑  收藏  举报