IOS开发~开机启动&无限后台运行&监听进程
非越狱情况下实现:
开机启动:App安装到IOS设备设备之后,无论App是否开启过,只要IOS设备重启,App就会随之启动;
无限后台运行:应用进入后台状态,可以无限后台运行,不被系统kill;
监听进程:可获IOS设备运行除系统外的App(包括正在运行和后台运行);
配置项目 plist文件
添加:
<key>UIBackgroundModes</key>
<array>
<string>voip</string>
</array>
功能类:ProccessHelper
- #import <Foundation/Foundation.h>
- @interface ProccessHelper : NSObject
- + (NSArray *)runningProcesses;
- @end
- #import "ProccessHelper.h"
- //#include<objc/runtime.h>
- #include <sys/sysctl.h>
- #include <stdbool.h>
- #include <sys/types.h>
- #include <unistd.h>
- #include <sys/sysctl.h>
- @implementation ProccessHelper
- //You can determine if your app is being run under the debugger with the following code from
- static bool AmIBeingDebugged(void)
- // Returns true if the current process is being debugged (either
- // running under the debugger or has a debugger attached post facto).
- {
- int junk;
- int mib[4];
- struct kinfo_proc info;
- size_t size;
- // Initialize the flags so that, if sysctl fails for some bizarre
- // reason, we get a predictable result.
- info.kp_proc.p_flag = 0;
- // Initialize mib, which tells sysctl the info we want, in this case
- // we're looking for information about a specific process ID.
- mib[0] = CTL_KERN;
- mib[1] = KERN_PROC;
- mib[2] = KERN_PROC_PID;
- mib[3] = getpid();
- // Call sysctl.
- size = sizeof(info);
- junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
- assert(junk == 0);
- // We're being debugged if the P_TRACED flag is set.
- return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
- }
- //返回所有正在运行的进程的 id,name,占用cpu,运行时间
- //使用函数int sysctl(int *, u_int, void *, size_t *, void *, size_t)
- + (NSArray *)runningProcesses
- {
- //指定名字参数,按照顺序第一个元素指定本请求定向到内核的哪个子系统,第二个及其后元素依次细化指定该系统的某个部分。
- //CTL_KERN,KERN_PROC,KERN_PROC_ALL 正在运行的所有进程
- int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL ,0};
- size_t miblen = 4;
- //值-结果参数:函数被调用时,size指向的值指定该缓冲区的大小;函数返回时,该值给出内核存放在该缓冲区中的数据量
- //如果这个缓冲不够大,函数就返回ENOMEM错误
- size_t size;
- //返回0,成功;返回-1,失败
- int st = sysctl(mib, miblen, NULL, &size, NULL, 0);
- struct kinfo_proc * process = NULL;
- struct kinfo_proc * newprocess = NULL;
- do
- {
- size += size / 10;
- newprocess = realloc(process, size);
- if (!newprocess)
- {
- if (process)
- {
- free(process);
- process = NULL;
- }
- return nil;
- }
- process = newprocess;
- st = sysctl(mib, miblen, process, &size, NULL, 0);
- } while (st == -1 && errno == ENOMEM);
- if (st == 0)
- {
- if (size % sizeof(struct kinfo_proc) == 0)
- {
- int nprocess = size / sizeof(struct kinfo_proc);
- if (nprocess)
- {
- NSMutableArray * array = [[NSMutableArray alloc] init];
- for (int i = nprocess - 1; i >= 0; i--)
- {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- NSString * processID = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_pid];
- NSString * processName = [[NSString alloc] initWithFormat:@"%s", process[i].kp_proc.p_comm];
- NSString * proc_CPU = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_estcpu];
- double t = [[NSDate date] timeIntervalSince1970] - process[i].kp_proc.p_un.__p_starttime.tv_sec;
- NSString * proc_useTiem = [[NSString alloc] initWithFormat:@"%f",t];
- NSString *startTime = [[NSString alloc] initWithFormat:@"%ld", process[i].kp_proc.p_un.__p_starttime.tv_sec];
- NSString * status = [[NSString alloc] initWithFormat:@"%d",process[i].kp_proc.p_flag];
- NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
- [dic setValue:processID forKey:@"ProcessID"];
- [dic setValue:processName forKey:@"ProcessName"];
- [dic setValue:proc_CPU forKey:@"ProcessCPU"];
- [dic setValue:proc_useTiem forKey:@"ProcessUseTime"];
- [dic setValue:proc_useTiem forKey:@"ProcessUseTime"];
- [dic setValue:startTime forKey:@"startTime"];
- // 18432 is the currently running application
- // 16384 is background
- [dic setValue:status forKey:@"status"];
- [processID release];
- [processName release];
- [proc_CPU release];
- [proc_useTiem release];
- [array addObject:dic];
- [startTime release];
- [status release];
- [dic release];
- [pool release];
- }
- free(process);
- process = NULL;
- //NSLog(@"array = %@",array);
- return array;
- }
- }
- }
- return nil;
- }
- @end
实现代码:
- systemprocessArray = [[NSMutableArray arrayWithObjects:
- @"kernel_task",
- @"launchd",
- @"UserEventAgent",
- @"wifid",
- @"syslogd",
- @"powerd",
- @"lockdownd",
- @"mediaserverd",
- @"mediaremoted",
- @"mDNSResponder",
- @"locationd",
- @"imagent",
- @"iapd",
- @"fseventsd",
- @"fairplayd.N81",
- @"configd",
- @"apsd",
- @"aggregated",
- @"SpringBoard",
- @"CommCenterClassi",
- @"BTServer",
- @"notifyd",
- @"MobilePhone",
- @"ptpd",
- @"afcd",
- @"notification_pro",
- @"notification_pro",
- @"syslog_relay",
- @"notification_pro",
- @"springboardservi",
- @"atc",
- @"sandboxd",
- @"networkd",
- @"lsd",
- @"securityd",
- @"lockbot",
- @"installd",
- @"debugserver",
- @"amfid",
- @"AppleIDAuthAgent",
- @"BootLaunch",
- @"MobileMail",
- @"BlueTool",
- nil] retain];
- - (void)applicationDidEnterBackground:(UIApplication *)application
- {
- while (1) {
- sleep(5);
- [self postMsg];
- }
- [[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:^{
- NSLog(@"KeepAlive");
- }];
- }
- - (void)applicationWillResignActive:(UIApplication *)application
- {
- }
- - (void)applicationWillEnterForeground:(UIApplication *)application
- {
- }
- - (void)applicationDidBecomeActive:(UIApplication *)application
- {
- }
- - (void)applicationWillTerminate:(UIApplication *)application
- {
- }
- #pragma mark -
- #pragma mark - User Method
- - (void) postMsg
- {
- //上传到服务器
- NSURL *url = [self getURL];
- NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
- NSError *error = nil;
- NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
- if (error) {
- NSLog(@"error:%@", [error localizedDescription]);
- }
- NSString *str = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
- NSLog(@"%@",str);
- }
- - (NSURL *) getURL
- {
- UIDevice *device = [UIDevice currentDevice];
- NSString* uuid = @"TESTUUID";
- NSString* manufacturer = @"apple";
- NSString* model = [device model];
- NSString* mobile = [device systemVersion];
- NSString *msg = [NSString stringWithFormat:@"Msg:%@ Time:%@", [self processMsg], [self getTime]];
- CFShow(msg);
- / 省略部分代码 /
- NSString *urlStr = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
- NSURL *url = [NSURL URLWithString:urlStr];
- return url;
- }
- - (BOOL) checkSystemProccess:(NSString *) proName
- {
- if ([systemprocessArray containsObject:proName]) {
- return YES;
- }
- return NO;
- }
- - (BOOL) checkFirst:(NSString *) string
- {
- NSString *str = [string substringToIndex:1];
- NSRange r = [@"ABCDEFGHIJKLMNOPQRSTUVWXWZ" rangeOfString:str];
- if (r.length > 0) {
- return YES;
- }
- return NO;
- }
- - (NSString *) processMsg
- {
- NSArray *proMsg = [ProccessHelper runningProcesses];
- if (proMsg == nil) {
- return nil;
- }
- NSMutableArray *proState = [NSMutableArray array];
- for (NSDictionary *dic in proMsg) {
- NSString *proName = [dic objectForKey:@"ProcessName"];
- if (![self checkSystemProccess:proName] && [self checkFirst:proName]) {
- NSString *proID = [dic objectForKey:@"ProcessID"];
- NSString *proStartTime = [dic objectForKey:@"startTime"];
- if ([[dic objectForKey:@"status"] isEqualToString:@"18432"]) {
- NSString *msg = [NSString stringWithFormat:@"ProcessName:%@ - ProcessID:%@ - StartTime:%@ Running:YES", proName, proID, proStartTime];
- [proState addObject:msg];
- } else {
- NSString *msg = [NSString stringWithFormat:@"ProcessName:%@ - ProcessID:%@ - StartTime:%@ Running:NO", proName, proID, proStartTime];
- [proState addObject:msg];
- }
- }
- }
- NSString *msg = [proState componentsJoinedByString:@"______"];
- return msg;
- }
- // 获取时间
- - (NSString *) getTime
- {
- NSDateFormatter *formatter =[[[NSDateFormatter alloc] init] autorelease];
- formatter.dateStyle = NSDateFormatterMediumStyle;
- formatter.timeStyle = NSDateFormatterMediumStyle;
- formatter.locale = [NSLocale currentLocale];
- NSDate *date = [NSDate date];
- [formatter setTimeStyle:NSDateFormatterMediumStyle];
- NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
- NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
- NSInteger unitFlags = NSYearCalendarUnit |
- NSMonthCalendarUnit |
- NSDayCalendarUnit |
- NSWeekdayCalendarUnit |
- NSHourCalendarUnit |
- NSMinuteCalendarUnit |
- NSSecondCalendarUnit;
- comps = [calendar components:unitFlags fromDate:date];
- int year = [comps year];
- int month = [comps month];
- int day = [comps day];
- int hour = [comps hour];
- int min = [comps minute];
- int sec = [comps second];
- NSString *time = [NSString stringWithFormat:@"%d-%d-%d %d:%d:%d", year, month, day, hour, min, sec];
- return time;
- }
- @end
IOS开发~开机启动&无限后台运行&监听进程的更多相关文章
- IOS高级开发~开机启动&无限后台运行&监听进程
一般来说, IOS很少给App后台运行的权限. 仅有的方式就是 VoIP. IOS少有的为VoIP应用提供了后台socket连接,定期唤醒并且随开机启动的权限.而这些就是IOS上实现VoIP App的 ...
- 安卓开机启动service后台运行
安卓开机启动service后台运行 Android开机启动时会发送一个广播android.intent.action.BOOT_COMPLETED,捕捉到这个广播,然后可以进行相应的操作,比如:通过捕 ...
- iOS开发UI篇—无限轮播(循环展示)
iOS开发UI篇—无限轮播(循环展示) 一.简单说明 之前的程序还存在一个问题,那就是不能循环展示,因为plist文件中只有五个数组,因此第一个和最后一个之后就没有了,下面介绍处理这种循环展示问题的小 ...
- iOS开发UI篇—无限轮播(功能完善)
iOS开发UI篇—无限轮播(功能完善) 一.自动滚动 添加并设置一个定时器,每个2.0秒,就跳转到下一条. 获取当前正在展示的位置. [self addNSTimer]; } -(void)addNS ...
- iOS开发UI篇—无限轮播(循环利用)
iOS开发UI篇—无限轮播(循环利用) 一.无限轮播 1.简单说明 在开发中常需要对广告或者是一些图片进行自动的轮播,也就是所谓的无限滚动. 在开发的时候,我们通常的做法是使用一个UIScrollV ...
- iOS开发UI篇—无限轮播(新闻数据展示)
iOS开发UI篇—无限轮播(新闻数据展示) 一.实现效果 二.实现步骤 1.前期准备 (1)导入数据转模型的第三方框架MJExtension (2)向项目中添加保存有“新闻”数据的pli ...
- 【iOS系列】-程序开启后台运行
[iOS系列]-程序开启后台运行 iOS程序是伪后台的运行,可是有时候我们需要让其在后台也要进行一些操作,我们可以让其伪装成音乐的APP,这样就可以让程序后台进行相关操作了,具体做法如下: 1:在Ap ...
- Android实训案例(六)——四大组件之一BroadcastReceiver的基本使用,拨号,短信,SD卡,开机,应用安装卸载监听
Android实训案例(六)--四大组件之一BroadcastReceiver的基本使用,拨号,短信,SD卡,开机,应用安装卸载监听 Android中四大组件的使用时重中之重,我这个阶段也不奢望能把他 ...
- asp.net core启动源码以及监听,到处理请求响应的过程
摘要 asp.net core发布至今已经将近6年了,很多人对于这一块还是有些陌生,或者说没接触过:接触过的,对于asp.net core整个启动过程,监听过程,以及请求过程,响应过程也是一知半解,可 ...
随机推荐
- 慢慢琢磨JVM
1 JVM简介 JVM是一个Javaer的最基本功底了,刚开始学Java的时候,一般都是从“Hello World”开始的,然后会写个复杂点class,然后再找一些开源框架,比如Spring,Hibe ...
- 12、jQuery知识总结-2
1.避免冲突 jQuery 使用 $ 符号作为 jQuery 的简介方式 <html> <head> <script type="text/javascript ...
- Appium Windows服务端GUI详解
Appium Windows服务端GUI各项的解释,从官方扒过来的,界面图标和最新版本有点不太一样,其他还是比较简单易懂的 原文https://github.com/appium/appium-dot ...
- PostgreSQL 行排序详解
在查询生成输出表之后,也就是在处理完选择列表之后,你还可以对输出表进行排序. 如果没有排序,那么行将以不可预测的顺序返回(实际顺序将取决于扫描和连接规划类型和在磁盘上的顺序, 但是肯定不能依赖这些东西 ...
- 【bzoj4281】[ONTAK2015]Związek Harcerstwa Bajtockiego 树上倍增+LCA
题目描述 给定一棵有n个点的无根树,相邻的点之间的距离为1,一开始你位于m点.之后你将依次收到k个指令,每个指令包含两个整数d和t,你需要沿着最短路在t步之内(包含t步)走到d点,如果不能走到,则停在 ...
- java连接mysql数据库 三 实现增删改查操作
同以前一样,先写一个数据库打开和关闭操作类 public class DBConnection { String driver = "com.mysql.jdbc.Driver"; ...
- GDKOI 游记
Day 0 坐和谐号去广州 非常奇怪的一点是,每次坐车去广州人都很少,但是坐车回来人都贼多...... 到酒店住下,出去吃完晚饭,lmy开始奶:明天考数据结构啊! zkw:为什么不考AC自动机和插头D ...
- element el-cascader设置默认值
原文:https://www.jianshu.com/p/b690d7fe6ec0 注意两点就行了 <el-form-item label="AP名称"> <el ...
- vue.js单文件组件中非父子组件的传值
最近在研究vue.js,总体来说还算可以,但是在web开发群里有一些人问在单文件组件开发模式中非父子组件如何传值的问题,今天在这里讲讲,希望对大家有所帮助! 在官网api中的这段讲解很少,也很模糊:官 ...
- 小甲鱼PE详解之资源(PE详解11)
原文出自:www.fishc.com 最近一直在安排第一届鱼C 学习班的事情,忙活了好一阵子,真是对不住大家,还大家久等了,这里要跟大家说声不好意思 ^_^ 今天我们来谈谈资源部分,资源部分可以说是 ...