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

来源:互联网 发布:软件创新设计方案 编辑:程序博客网 时间:2024/04/30 19:55

轻松一刻  


非越狱情况下实现:

http://goo.gl/ZBrjtt

开机启动: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, NULL0);    
  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, NULL0);    
  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, NULL0);    
  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    

0 0
原创粉丝点击