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

原文地址: http://blog.csdn.net/lizhongfu2013/article/details/9839217

非越狱情况下实现:

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

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

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


配置项目 plist文件

添加:

<key>UIBackgroundModes</key>

<array>

<string>voip</string>

</array>


功能类:ProccessHelper

  1. #import <Foundation/Foundation.h>  
  2.   
  3. @interface ProccessHelper : NSObject  
  4.   
  5. + (NSArray *)runningProcesses;  
  6.   
  7. @end  

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值