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

非越狱情况下实现:

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

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

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

配置项目 plist文件

添加:

<key>UIBackgroundModes</key>

<array>

<string>voip</string>

</array>

功能类:ProccessHelper

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

 

实现代码:

  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] retain];

 

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