Get usage time for individual apps programmatically iOS

1.4k views Asked by At

Is it possible to get the usage time for each app on my iPhone programatically? I want to create an app which tells me how much time I spend on each app on my iPhone.

3

There are 3 answers

1
lukaswelte On BEST ANSWER

Short answer: NO

Longer answer: Just using a jailbreak.

0
neilco On

No. Each app is isolated in its own sandbox. You can only receive usage information for your apps and not those by other developers. And that's only if you add that functionality yourself.

0
Vinoth Kannan On

From this code you can get starting time of the process

- (NSArray *)runningProcesses
{

int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
size_t miblen = 4;

size_t size;
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);
        }

        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)
        {

            array = [[NSMutableArray alloc] init];

            for (int i = nprocess - 1; i >= 0; i--)
            {

                processID = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_pid];
                processName = [[NSString alloc] initWithFormat:@"%s", process[i].kp_proc.p_comm];
                NSString * processStartTime = [[NSString alloc] initWithFormat:@"%ld", process[i].kp_proc.p_starttime.tv_sec];
                NSString * priority = [[NSString alloc] initWithFormat:@"%hhu", process[i].kp_proc.p_priority];
                NSString * status = [[NSString alloc] initWithFormat:@"%d", process[i].kp_proc.p_stat];

                NSDictionary * dict = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:processID, processName,processStartTime,priority,status, nil] forKeys:[NSArray arrayWithObjects:@"ProcessID", @"ProcessName",@"Time", @"Priority",@"Status", nil]];
                [array addObject:dict];
                 NSLog(@"PID %d",process[i].kp_proc.p_pid);
            }

            free(process);
            NSLog(@"Array %@",array);
        }
    }
}
return nil;

}

Blockquote