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

时间:2025-02-15 20:03:44

非越狱情况下实现:

开机启动: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
  1. #import "ProccessHelper.h"
  2. //#include<objc/runtime.h>
  3. #include <sys/sysctl.h>
  4. #include <stdbool.h>
  5. #include <sys/types.h>
  6. #include <unistd.h>
  7. #include <sys/sysctl.h>
  8. @implementation ProccessHelper
  9. //You can determine if your app is being run under the debugger with the following code from
  10. static bool AmIBeingDebugged(void)
  11. // Returns true if the current process is being debugged (either
  12. // running under the debugger or has a debugger attached post facto).
  13. {
  14. int                 junk;
  15. int                 mib[4];
  16. struct kinfo_proc   info;
  17. size_t              size;
  18. // Initialize the flags so that, if sysctl fails for some bizarre
  19. // reason, we get a predictable result.
  20. info.kp_proc.p_flag = 0;
  21. // Initialize mib, which tells sysctl the info we want, in this case
  22. // we're looking for information about a specific process ID.
  23. mib[0] = CTL_KERN;
  24. mib[1] = KERN_PROC;
  25. mib[2] = KERN_PROC_PID;
  26. mib[3] = getpid();
  27. // Call sysctl.
  28. size = sizeof(info);
  29. junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
  30. assert(junk == 0);
  31. // We're being debugged if the P_TRACED flag is set.
  32. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  33. }
  34. //返回所有正在运行的进程的 id,name,占用cpu,运行时间
  35. //使用函数int   sysctl(int *, u_int, void *, size_t *, void *, size_t)
  36. + (NSArray *)runningProcesses
  37. {
  38. //指定名字参数,按照顺序第一个元素指定本请求定向到内核的哪个子系统,第二个及其后元素依次细化指定该系统的某个部分。
  39. //CTL_KERN,KERN_PROC,KERN_PROC_ALL 正在运行的所有进程
  40. int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL ,0};
  41. size_t miblen = 4;
  42. //值-结果参数:函数被调用时,size指向的值指定该缓冲区的大小;函数返回时,该值给出内核存放在该缓冲区中的数据量
  43. //如果这个缓冲不够大,函数就返回ENOMEM错误
  44. size_t size;
  45. //返回0,成功;返回-1,失败
  46. int st = sysctl(mib, miblen, NULL, &size, NULL, 0);
  47. struct kinfo_proc * process = NULL;
  48. struct kinfo_proc * newprocess = NULL;
  49. do
  50. {
  51. size += size / 10;
  52. newprocess = realloc(process, size);
  53. if (!newprocess)
  54. {
  55. if (process)
  56. {
  57. free(process);
  58. process = NULL;
  59. }
  60. return nil;
  61. }
  62. process = newprocess;
  63. st = sysctl(mib, miblen, process, &size, NULL, 0);
  64. } while (st == -1 && errno == ENOMEM);
  65. if (st == 0)
  66. {
  67. if (size % sizeof(struct kinfo_proc) == 0)
  68. {
  69. int nprocess = size / sizeof(struct kinfo_proc);
  70. if (nprocess)
  71. {
  72. NSMutableArray * array = [[NSMutableArray alloc] init];
  73. for (int i = nprocess - 1; i >= 0; i--)
  74. {
  75. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  76. NSString * processID = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_pid];
  77. NSString * processName = [[NSString alloc] initWithFormat:@"%s", process[i].kp_proc.p_comm];
  78. NSString * proc_CPU = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_estcpu];
  79. double t = [[NSDate date] timeIntervalSince1970] - process[i].kp_proc.p_un.__p_starttime.tv_sec;
  80. NSString * proc_useTiem = [[NSString alloc] initWithFormat:@"%f",t];
  81. NSString *startTime = [[NSString alloc] initWithFormat:@"%ld", process[i].kp_proc.p_un.__p_starttime.tv_sec];
  82. NSString * status = [[NSString alloc] initWithFormat:@"%d",process[i].kp_proc.p_flag];
  83. NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
  84. [dic setValue:processID forKey:@"ProcessID"];
  85. [dic setValue:processName forKey:@"ProcessName"];
  86. [dic setValue:proc_CPU forKey:@"ProcessCPU"];
  87. [dic setValue:proc_useTiem forKey:@"ProcessUseTime"];
  88. [dic setValue:proc_useTiem forKey:@"ProcessUseTime"];
  89. [dic setValue:startTime forKey:@"startTime"];
  90. // 18432 is the currently running application
  91. // 16384 is background
  92. [dic setValue:status forKey:@"status"];
  93. [processID release];
  94. [processName release];
  95. [proc_CPU release];
  96. [proc_useTiem release];
  97. [array addObject:dic];
  98. [startTime release];
  99. [status release];
  100. [dic release];
  101. [pool release];
  102. }
  103. free(process);
  104. process = NULL;
  105. //NSLog(@"array = %@",array);
  106. return array;
  107. }
  108. }
  109. }
  110. return nil;
  111. }
  112. @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. }
    1. [[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:^{
    2. NSLog(@"KeepAlive");
    3. }];
    4. }
    5. - (void)applicationWillResignActive:(UIApplication *)application
    6. {
    7. }
    8. - (void)applicationWillEnterForeground:(UIApplication *)application
    9. {
    10. }
    11. - (void)applicationDidBecomeActive:(UIApplication *)application
    12. {
    13. }
    14. - (void)applicationWillTerminate:(UIApplication *)application
    15. {
    16. }
    17. #pragma mark -
    18. #pragma mark - User Method
    19. - (void) postMsg
    20. {
    21. //上传到服务器
    22. NSURL *url = [self getURL];
    23. NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    24. NSError *error = nil;
    25. NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
    26. if (error) {
    27. NSLog(@"error:%@", [error localizedDescription]);
    28. }
    29. NSString *str = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
    30. NSLog(@"%@",str);
    31. }
    32. - (NSURL *) getURL
    33. {
    34. UIDevice *device = [UIDevice currentDevice];
    35. NSString* uuid = @"TESTUUID";
    36. NSString* manufacturer = @"apple";
    37. NSString* model = [device model];
    38. NSString* mobile = [device systemVersion];
    39. NSString *msg = [NSString stringWithFormat:@"Msg:%@  Time:%@", [self processMsg], [self getTime]];
    40. CFShow(msg);
    41. /  省略部分代码  /
    42. NSString *urlStr = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    43. NSURL *url = [NSURL URLWithString:urlStr];
    44. return url;
    45. }
    46. - (BOOL) checkSystemProccess:(NSString *) proName
    47. {
    48. if ([systemprocessArray containsObject:proName]) {
    49. return YES;
    50. }
    51. return NO;
    52. }
    53. - (BOOL) checkFirst:(NSString *) string
    54. {
    55. NSString *str = [string substringToIndex:1];
    56. NSRange r = [@"ABCDEFGHIJKLMNOPQRSTUVWXWZ" rangeOfString:str];
    57. if (r.length > 0) {
    58. return YES;
    59. }
    60. return NO;
    61. }
    62. - (NSString *) processMsg
    63. {
    64. NSArray *proMsg = [ProccessHelper runningProcesses];
    65. if (proMsg == nil) {
    66. return nil;
    67. }
    68. NSMutableArray *proState = [NSMutableArray array];
    69. for (NSDictionary *dic in proMsg) {
    70. NSString *proName = [dic objectForKey:@"ProcessName"];
    71. if (![self checkSystemProccess:proName] && [self checkFirst:proName]) {
    72. NSString *proID = [dic objectForKey:@"ProcessID"];
    73. NSString *proStartTime = [dic objectForKey:@"startTime"];
    74. if ([[dic objectForKey:@"status"] isEqualToString:@"18432"]) {
    75. NSString *msg = [NSString stringWithFormat:@"ProcessName:%@ - ProcessID:%@ - StartTime:%@ Running:YES", proName, proID, proStartTime];
    76. [proState addObject:msg];
    77. } else {
    78. NSString *msg = [NSString stringWithFormat:@"ProcessName:%@ - ProcessID:%@ - StartTime:%@ Running:NO", proName, proID, proStartTime];
    79. [proState addObject:msg];
    80. }
    81. }
    82. }
    83. NSString *msg = [proState componentsJoinedByString:@"______"];
    84. return msg;
    85. }
    86. // 获取时间
    87. - (NSString *) getTime
    88. {
    89. NSDateFormatter *formatter =[[[NSDateFormatter alloc] init] autorelease];
    90. formatter.dateStyle = NSDateFormatterMediumStyle;
    91. formatter.timeStyle = NSDateFormatterMediumStyle;
    92. formatter.locale = [NSLocale currentLocale];
    93. NSDate *date = [NSDate date];
    94. [formatter setTimeStyle:NSDateFormatterMediumStyle];
    95. NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    96. NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
    97. NSInteger unitFlags = NSYearCalendarUnit |
    98. NSMonthCalendarUnit |
    99. NSDayCalendarUnit |
    100. NSWeekdayCalendarUnit |
    101. NSHourCalendarUnit |
    102. NSMinuteCalendarUnit |
    103. NSSecondCalendarUnit;
    104. comps = [calendar components:unitFlags fromDate:date];
    105. int year = [comps year];
    106. int month = [comps month];
    107. int day = [comps day];
    108. int hour = [comps hour];
    109. int min = [comps minute];
    110. int sec = [comps second];
    111. NSString *time = [NSString stringWithFormat:@"%d-%d-%d %d:%d:%d", year, month, day, hour, min, sec];
    112. return time;
    113. }
    114. @end