3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *
16 | */
17 |
18 | package com.wenming.library.processutil.models;
19 |
20 | import android.os.Parcel;
21 | import android.os.Parcelable;
22 | import android.text.TextUtils;
23 |
24 | import java.io.IOException;
25 |
26 | public class AndroidProcess implements Parcelable {
27 |
28 | /**
29 | * Get the name of a running process.
30 | *
31 | * @param pid
32 | * the process id.
33 | * @return the name of the process.
34 | * @throws IOException
35 | * if the file does not exist or we don't have read permissions.
36 | */
37 | static String getProcessName(int pid) throws IOException {
38 | String cmdline = null;
39 | try {
40 | cmdline = ProcFile.readFile(String.format("/proc/%d/cmdline", pid)).trim();
41 | } catch (IOException ignored) {
42 | }
43 | if (TextUtils.isEmpty(cmdline)) {
44 | return Stat.get(pid).getComm();
45 | }
46 | return cmdline;
47 | }
48 |
49 | /** the process name */
50 | public final String name;
51 |
52 | /** the process id */
53 | public final int pid;
54 |
55 | /**
56 | * AndroidProcess constructor
57 | *
58 | * @param pid
59 | * the process id
60 | * @throws IOException
61 | * if /proc/[pid] does not exist or we don't have read access.
62 | */
63 | public AndroidProcess(int pid) throws IOException {
64 | this.pid = pid;
65 | this.name = getProcessName(pid);
66 | }
67 |
68 | /**
69 | * Read the contents of a file in /proc/[pid]/[filename].
70 | *
71 | * @param filename
72 | * the relative path to the file.
73 | * @return the contents of the file.
74 | * @throws IOException
75 | * if the file does not exist or we don't have read permissions.
76 | */
77 | public String read(String filename) throws IOException {
78 | return ProcFile.readFile(String.format("/proc/%d/%s", pid, filename));
79 | }
80 |
81 | /**
82 | * /proc/[pid]/attr/current (since Linux 2.6.0)
83 | *
84 | * The contents of this file represent the current security attributes of the process.
85 | *
86 | * In SELinux, this file is used to get the security context of a process. Prior to Linux
87 | * 2.6.11, this file could not be used to set the security context (a write was always denied),
88 | * since SELinux limited process security transitions to execve(2) (see the description of
89 | * /proc/[pid]/attr/exec, below). ince Linux 2.6.11, SELinux lifted this restriction and began
90 | * supporting "set" operations via writes to this node if authorized by policy, although use of
91 | * this operation is only suitable for applications that are trusted to maintain any desired
92 | * separation between the old and new security contexts. Prior to Linux 2.6.28, SELinux did not
93 | * allow threads within a multi- threaded process to set their security context via this node as
94 | * it would yield an inconsistency among the security contexts of the threads sharing the same
95 | * memory space. Since Linux 2.6.28, SELinux lifted this restriction and began supporting "set"
96 | * operations for threads within a multithreaded process if the new security context is bounded
97 | * by the old security context, where the bounded relation is defined in policy and guarantees
98 | * that the new security context has a subset of the permissions of the old security context.
99 | * Other security modules may choose to support "set" operations via writes to this node.
100 | *
101 | * @return the contents of /proc/[pid]/attr/current
102 | * @throws IOException
103 | * if the file does not exist or we don't have read permissions.
104 | */
105 | public String attr_current() throws IOException {
106 | return read("attr/current");
107 | }
108 |
109 | /**
110 | * /proc/[pid]/cmdline
111 | *
112 | * This read-only file holds the complete command line for the process, unless the process is
113 | * a zombie. In the latter case, there is nothing in this file: that is, a read on this file will
114 | * return 0 characters. The command-line arguments appear in this file as a set of strings
115 | * separated by null bytes ('\0'), with a further null byte after the last string.
116 | *
117 | * @return the name of the process. (note: process name may be empty. In case it is empty get
118 | * the process name from /proc/[pid]/stat).
119 | * @throws IOException
120 | * if the file does not exist or we don't have read permissions.
121 | * @see #name
122 | */
123 | public String cmdline() throws IOException {
124 | return read("cmdline");
125 | }
126 |
127 | /**
128 | * /proc/[pid]/cgroup (since Linux 2.6.24)
129 | *
130 | * This file describes control groups to which the process/task belongs. For each cgroup
131 | * hierarchy there is one entry containing colon-separated fields of the form:
132 | *
133 | * 5:cpuacct,cpu,cpuset:/daemons
134 | *
135 | * The colon-separated fields are, from left to right:
136 | *
137 | *
138 | * - hierarchy ID number
139 | * - set of subsystems bound to the hierarchy
140 | * - control group in the hierarchy to which the process belongs
141 | *
142 | *
143 | * This file is present only if the CONFIG_CGROUPS kernel configuration option is enabled.
144 | *
145 | * @return the {@link Cgroup} for this process
146 | * @throws IOException
147 | */
148 | public Cgroup cgroup() throws IOException {
149 | return Cgroup.get(pid);
150 | }
151 |
152 | /**
153 | * /proc/[pid]/oom_score (since Linux 2.6.11)
154 | *
155 | * This file displays the current score that the kernel gives to this process for the
156 | * purpose of selecting a process for the OOM-killer. A higher score means that the
157 | * process is more likely to be selected by the OOM-killer.
158 | *
159 | * The basis for this score is the amount of memory used by the process, with
160 | * increases (+) or decreases (-) for factors including:
161 | *
162 | *
163 | * - whether the process creates a lot of children using fork(2)(+);
164 | * - whether the process has been running a long time, or has used a lot of CPU time (-);
165 | * - whether the process has a low nice value (i.e., > 0) (+);
166 | * - whether the process is privileged (-); and
167 | * - whether the process is making direct hardware access (-).
168 | *
169 | *
170 | * The oom_score also reflects the adjustment specified by the oom_score_adj
171 | * or oom_adj setting for the process.
172 | *
173 | * @return the oom_score value for this process
174 | * @throws IOException
175 | * if the file does not exist or we don't have read permissions.
176 | */
177 | public int oom_score() throws IOException {
178 | return Integer.parseInt(read("oom_score"));
179 | }
180 |
181 | /**
182 | * /proc/[pid]/oom_adj (since Linux 2.6.11)
183 | *
184 | * This file can be used to adjust the score used to select which process should be killed in
185 | * an out-of-memory (OOM) situation. The kernel uses this value for a bit-shift operation of the
186 | * process's oom_score value: valid values are in the* range -16 to +15, plus the special value
187 | * -17, which disables OOM-killing altogether for this process. A positive score increases the
188 | * likelihood of this process being killed by the OOM-killer; a negative score decreases the
189 | * likelihood.
190 | *
191 | * The default value for this file is 0; a new process inherits its parent's oom_adj setting.
192 | * A process must be privileged (CAP_SYS_RESOURCE) to update this file.
193 | *
194 | * Since Linux 2.6.36, use of this file is deprecated in favor of
195 | * /proc/[pid]/oom_score_adj.
196 | *
197 | * @return the oom_adj value for this process
198 | * @throws IOException
199 | * if the file does not exist or we don't have read permissions.
200 | */
201 | public int oom_adj() throws IOException {
202 | return Integer.parseInt(read("oom_adj"));
203 | }
204 |
205 | /**
206 | * /proc/[pid]/oom_score_adj (since Linux 2.6.36)
207 | *
208 | * This file can be used to adjust the badness heuristic used to select which process gets
209 | * killed in out-of-memory conditions.
210 | *
211 | * The badness heuristic assigns a value to each candidate task ranging from 0 (never kill) to
212 | * 1000 (always kill) to determine which process is targeted. The units are roughly a proportion
213 | * along that range of allowed memory the process may allocate from, based on an estimation of
214 | * its current memory and swap use. For example, if a task is using all allowed memory, its
215 | * badness score will be 1000. If it is using half of its allowed memory, its score will be
216 | * 500.
217 | *
218 | * There is an additional factor included in the badness score: root processes are given 3%
219 | * extra memory over other tasks.
220 | *
221 | * The amount of "allowed" memory depends on the context in which the OOM-killer was called.
222 | * If it is due to the memory assigned to the allocating task's cpuset being exhausted, the
223 | * allowed memory represents the set of mems assigned to that cpuset (see cpuset(7)). If it is
224 | * due to a mempolicy's node(s) being exhausted, the allowed memory represents the set of
225 | * mempolicy nodes. If it is due to a memory limit (or swap limit) being reached, the allowed
226 | * memory is that configured limit. Finally, if it is due to the entire system being out of
227 | * memory, the allowed memory represents all allocatable resources.
228 | *
229 | * The value of oom_score_adj is added to the badness score before it is used to determine
230 | * which task to kill. Acceptable values range from -1000 (OOM_SCORE_ADJ_MIN) to +1000
231 | * (OOM_SCORE_ADJ_MAX). This allows user space to control the preference for OOM-killing, ranging
232 | * from always preferring a certain task or completely disabling it from OOM killing. The lowest
233 | * possible value, -1000, is equivalent to disabling OOM- killing entirely for that task, since
234 | * it will always report a badness score of 0.
235 | *
236 | * Consequently, it is very simple for user space to define the amount of memory to consider
237 | * for each task. Setting a oom_score_adj value of +500, for example, is roughly equivalent to
238 | * allowing the remainder of tasks sharing the same system, cpuset, mempolicy, or memory
239 | * controller resources to use at least 50% more memory. A value of -500, on the other hand,
240 | * would be roughly equivalent to discounting 50% of the task's allowed memory from being
241 | * considered as scoring against the task.
242 | *
243 | * For backward compatibility with previous kernels, /proc/[pid]/oom_adj can still be used to
244 | * tune the badness score. Its value is scaled linearly with oom_score_adj.
245 | *
246 | * Writing to /proc/[pid]/oom_score_adj or /proc/[pid]/oom_adj will change the other with its
247 | * scaled value.
248 | *
249 | * @return the oom_score_adj value for this process
250 | * @throws IOException
251 | * if the file does not exist or we don't have read permissions.
252 | */
253 | public int oom_score_adj() throws IOException {
254 | return Integer.parseInt(read("oom_score_adj"));
255 | }
256 |
257 | /**
258 | * /proc/[pid]/stat
259 | *
260 | * Status information about the process. This is used by ps(1). It is defined in the kernel
261 | * source file fs/proc/array.c.
262 | *
263 | * The fields, in order, with their proper scanf(3) format specifiers, are:
264 | *
265 | *
266 | *
267 | * - pid %d The process ID.
268 | *
269 | * - comm %s The filename of the executable, in parentheses. This is visible whether or not
270 | * the executable is swapped out.
271 | *
272 | * - state %c One of the following characters, indicating process state:
273 | *
274 | * - R Running
275 | * - S Sleeping in an interruptible wait
276 | * - D Waiting in uninterruptible disk sleep
277 | * - Z Zombie
278 | * - T Stopped (on a signal) or (before Linux 2.6.33) trace stopped
279 | * - t Tracing stop (Linux 2.6.33 onward)
280 | * - W Paging (only before Linux 2.6.0)
281 | * - X Dead (from Linux 2.6.0 onward)
282 | * - x Dead (Linux 2.6.33 to 3.13 only)
283 | * - K Wakekill (Linux 2.6.33 to 3.13 only)
284 | * - W Waking (Linux 2.6.33 to 3.13 only)
285 | * - P Parked (Linux 3.9 to 3.13 only)
286 | *
287 | *
288 | *
289 | * - ppid %d The PID of the parent of this process.
290 | *
291 | * - pgrp %d The process group ID of the process.
292 | *
293 | * - session %d The session ID of the process.
294 | *
295 | * - tty_nr %d The controlling terminal of the process. (The minor device number is contained
296 | * in the combination of bits 31 to 20 and 7 to 0; the major device number is in bits 15 to 8.)
297 | *
298 | *
299 | * - tpgid %d The ID of the foreground process group of the controlling terminal of the
300 | * process.
301 | *
302 | * - flags %u The kernel flags word of the process. For bit meanings, see the PF_* defines in
303 | * the Linux kernel source file include/linux/sched.h. Details depend on the kernel version.
304 | * The format for this field was %lu before Linux 2.6.
305 | *
306 | * - minflt %lu The number of minor faults the process has made which have not required
307 | * loading a memory page from disk.
308 | *
309 | * - cminflt %lu The number of minor faults that the process's waited-for children have
310 | * made
311 | *
312 | * - majflt %lu The number of major faults the process has made which have required loading a
313 | * memory page from disk.
314 | *
315 | * - cmajflt %lu The number of major faults that the process's waited-for children have
316 | * made
317 | *
318 | * - utime %lu Amount of time that this process has been scheduled in user mode, measured in
319 | * clock ticks (divide by sysconf(_SC_CLK_TCK)). This includes guest time, guest_time (time
320 | * spent running a virtual CPU, see below), so that applications that are not aware of the guest
321 | * time field do not lose that time from their calculations.
322 | *
323 | * - stime %lu Amount of time that this process has been scheduled in kernel mode, measured
324 | * in clock ticks (divide by sysconf(_SC_CLK_TCK)).
325 | *
326 | * - cutime %ld Amount of time that this process's waited-for children have been scheduled in
327 | * user mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK)). (See also times(2).)
328 | * This includes guest time, cguest_time (time spent running a virtual CPU, see below).
329 | *
330 | * - cstime %ld Amount of time that this process's waited-for children have been scheduled in
331 | * kernel mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK)).
332 | *
333 | * - priority %ld (Explanation for Linux 2.6) For processes running a real-time scheduling
334 | * policy (policy below; see sched_setscheduler(2)), this is the negated scheduling priority,
335 | * minus one; that is, a number in the range -2 to -100, corresponding to real-time priorities 1
336 | * to 99. For processes running under a non-real-time scheduling policy, this is the raw nice
337 | * value (setpriority(2)) as represented in the kernel. The kernel stores nice values as numbers
338 | * in the range 0 (high) to 39 (low), corresponding to the user-visible nice range of -20 to 19.
339 | * Before Linux 2.6, this was a scaled value based on the scheduler weighting given to this
340 | * process
341 | *
342 | * - nice %ld The nice value (see setpriority(2)), a value in the range 19 (low priority) to
343 | * -20 (high priority).
344 | *
345 | * - num_threads %ld Number of threads in this process (since Linux 2.6). Before kernel 2.6,
346 | * this field was hard coded to 0 as a placeholder for an earlier removed field.
347 | *
348 | * - itrealvalue %ld The time in jiffies before the next SIGALRM is sent to the process due
349 | * to an interval timer. Since kernel 2.6.17, this field is no longer maintained, and is hard
350 | * coded as 0.
351 | *
352 | * - starttime %llu The time the process started after system boot. In kernels before Linux
353 | * 2.6, this value was expressed in jiffies. Since Linux 2.6, the value is expressed in clock
354 | * ticks (divide by sysconf(_SC_CLK_TCK)).
355 | *
356 | * - The format for this field was %lu before Linux 2.6. (23) vsize %lu Virtual memory size
357 | * in bytes.
358 | *
359 | * - rss %ld Resident Set Size: number of pages the process has in real memory. This is just
360 | * the pages which count toward text, data, or stack space. This does not include pages which
361 | * have not been demand-loaded in, or which are swapped out.
362 | *
363 | * - rsslim %lu Current soft limit in bytes on the rss of the process; see the description of
364 | * RLIMIT_RSS in getrlimit(2).
365 | *
366 | * - startcode %lu The address above which program text can run.
367 | *
368 | * - endcode %lu The address below which program text can run.
369 | *
370 | * - startstack %lu The address of the start (i.e., bottom) of the stack.
371 | *
372 | * - kstkesp %lu The current value of ESP (stack pointer), as found in the kernel stack page
373 | * for the process.
374 | *
375 | * - kstkeip %lu The current EIP (instruction pointer).
376 | *
377 | * - signal %lu The bitmap of pending signals, displayed as a decimal number. Obsolete,
378 | * because it does not provide information on real-time signals; use /proc/[pid]/status
379 | * instead
380 | *
381 | * - blocked %lu The bitmap of blocked signals, displayed as a decimal number. Obsolete,
382 | * because it does not provide information on real-time signals; use /proc/[pid]/status
383 | * instead
384 | *
385 | * - sigignore %lu The bitmap of ignored signals, displayed as a decimal number. Obsolete,
386 | * because it does not provide information on real-time signals; use /proc/[pid]/status
387 | * instead
388 | *
389 | * - sigcatch %lu The bitmap of caught signals, displayed as a decimal number. Obsolete,
390 | * because it does not provide information on real-time signals; use /proc/[pid]/status
391 | * instead.
392 | *
393 | * - wchan %lu This is the "channel" in which the process is waiting. It is the address of a
394 | * location in the kernel where the process is sleeping. The corresponding symbolic name can be
395 | * found in /proc/[pid]/wchan.
396 | *
397 | * - nswap %lu Number of pages swapped (not maintained).
398 | *
399 | * - cnswap %lu Cumulative nswap for child processes (not maintained).
400 | *
401 | * - exit_signal %d (since Linux 2.1.22) Signal to be sent to parent when we die.
402 | *
403 | * - processor %d (since Linux 2.2.8) CPU number last executed on.
404 | *
405 | * - rt_priority %u (since Linux 2.5.19) Real-time scheduling priority, a number in the
406 | * range 1 to 99 for processes scheduled under a real-time policy, or 0, for non-real-time
407 | * processes (see sched_setscheduler(2)).
408 | *
409 | * - policy %u (since Linux 2.5.19) Scheduling policy (see sched_setscheduler(2)). Decode
410 | * using the SCHED_* constants in linux/sched.h. The format for this field was %lu before Linux
411 | * 2.6.22.
412 | *
413 | * - delayacct_blkio_ticks %llu (since Linux 2.6.18) Aggregated block I/O delays, measured
414 | * in clock ticks (centiseconds).
415 | *
416 | * - guest_time %lu (since Linux 2.6.24) Guest time of the process (time spent running a
417 | * virtual CPU for a guest operating system), measured in clock ticks (divide by
418 | * sysconf(_SC_CLK_TCK)).
419 | *
420 | * - cguest_time %ld (since Linux 2.6.24) Guest time of the process's children, measured in
421 | * clock ticks (divide by sysconf(_SC_CLK_TCK)).
422 | *
423 | * - start_data %lu (since Linux 3.3) Address above which program initialized and
424 | * uninitialized (BSS) data are placed.
425 | *
426 | * - end_data %lu (since Linux 3.3) Address below which program initialized and
427 | * uninitialized (BSS) data are placed.
428 | *
429 | * - start_brk %lu (since Linux 3.3) Address above which program heap can be expanded with
430 | * brk(2).
431 | *
432 | * - arg_start %lu (since Linux 3.5) Address above which program command-line arguments
433 | * (argv) are placed.
434 | *
435 | * - arg_end %lu (since Linux 3.5) Address below program command-line arguments (argv) are
436 | * placed.
437 | *
438 | * - env_start %lu (since Linux 3.5) Address above which program environment is placed.
439 | *
440 | * - env_end %lu (since Linux 3.5) Address below which program environment is placed.
441 | *
442 | * - exit_code %d (since Linux 3.5) The thread's exit status in the form reported by
443 | * waitpid(2).
444 | *
445 | *
446 | *
447 | * @return the {@link Stat} for this process
448 | * @throws IOException
449 | * if the file does not exist or we don't have read permissions.
450 | */
451 | public Stat stat() throws IOException {
452 | return Stat.get(pid);
453 | }
454 |
455 | /**
456 | * Provides information about memory usage, measured in pages.
457 | *
458 | * The columns are:
459 | *
460 | *
461 | * - size (1) total program size (same as VmSize in /proc/[pid]/status)
462 | * - resident (2) resident set size (same as VmRSS in /proc/[pid]/status)
463 | * - share (3) shared pages (i.e., backed by a file)
464 | * - text (4) text (code)
465 | * - lib (5) library (unused in Linux 2.6)
466 | * - data (6) data + stack
467 | * - dt (7) dirty pages (unused in Linux 2.6)
468 | *
469 | *
470 | * @return the {@link Statm} for this process
471 | * @throws IOException
472 | * if the file does not exist or we don't have read permissions.
473 | */
474 | public Statm statm() throws IOException {
475 | return Statm.get(pid);
476 | }
477 |
478 | /**
479 | * /proc/[pid]/status
480 | *
481 | * Provides much of the information in /proc/[pid]/stat and /proc/[pid]/statm in a format
482 | * that's
483 | * easier for humans to parse.
484 | *
485 | * Here's an example:
486 | *
487 | *
488 | * $ cat /proc/$$/status
489 | * Name: bash
490 | * State: S (sleeping)
491 | * Tgid: 3515
492 | * Pid: 3515
493 | * PPid: 3452
494 | * TracerPid: 0
495 | * Uid: 1000 1000 1000 1000
496 | * Gid: 100 100 100 100
497 | * FDSize: 256
498 | * Groups: 16 33 100
499 | * VmPeak: 9136 kB
500 | * VmSize: 7896 kB
501 | * VmLck: 0 kB
502 | * VmPin: 0 kB
503 | * VmHWM: 7572 kB
504 | * VmRSS: 6316 kB
505 | * VmData: 5224 kB
506 | * VmStk: 88 kB
507 | * VmExe: 572 kB
508 | * VmLib: 1708 kB
509 | * VmPMD: 4 kB
510 | * VmPTE: 20 kB
511 | * VmSwap: 0 kB
512 | * Threads: 1
513 | * SigQ: 0/3067
514 | * SigPnd: 0000000000000000
515 | * ShdPnd: 0000000000000000
516 | * SigBlk: 0000000000010000
517 | * SigIgn: 0000000000384004
518 | * SigCgt: 000000004b813efb
519 | * CapInh: 0000000000000000
520 | * CapPrm: 0000000000000000
521 | * CapEff: 0000000000000000
522 | * CapBnd: ffffffffffffffff
523 | * Seccomp: 0
524 | * Cpus_allowed: 00000001
525 | * Cpus_allowed_list: 0
526 | * Mems_allowed: 1
527 | * Mems_allowed_list: 0
528 | * voluntary_ctxt_switches: 150
529 | * nonvoluntary_ctxt_switches: 545
530 | *
531 | *
532 | * The fields are as follows:
533 | *
534 | *
535 | * - Name: Command run by this process.
536 | * - State: Current state of the process. One of "R (running)", "S (sleeping)", "D (disk
537 | * sleep)",
538 | * "T (stopped)", "T (tracing stop)", "Z (zombie)", or "X (dead)".
539 | * - Tgid: Thread group ID (i.e., Process ID).
540 | * - Pid: Thread ID (see gettid(2)).
541 | * - PPid: PID of parent process.
542 | * - TracerPid: PID of process tracing this process (0 if not being traced).
543 | * - Uid, Gid: Real, effective, saved set, and filesystem UIDs (GIDs).
544 | * - FDSize: Number of file descriptor slots currently allocated.
545 | * - Groups: Supplementary group list.
546 | * - VmPeak: Peak virtual memory size.
547 | * - VmSize: Virtual memory size.
548 | * - VmLck: Locked memory size (see mlock(3)).
549 | * - VmPin: Pinned memory size (since Linux 3.2). These are pages that can't be moved because
550 | * something needs to directly access physical memory.
551 | * - VmHWM: Peak resident set size ("high water mark").
552 | * - VmRSS: Resident set size.
553 | * - VmData, VmStk, VmExe: Size of data, stack, and text segments.
554 | * - VmLib: Shared library code size.
555 | * - VmPTE: Page table entries size (since Linux 2.6.10).
556 | * - VmPMD: Size of second-level page tables (since Linux 4.0).
557 | * - VmSwap: Swapped-out virtual memory size by anonymous private pages; shmem swap usage is
558 | * not
559 | * included (since Linux 2.6.34).
560 | * - Threads: Number of threads in process containing this thread.
561 | * - SigQ: This field contains two slash-separated numbers that relate to queued signals for
562 | * the
563 | * real user ID of this process. The first of these is the number of currently queued signals
564 | * for
565 | * this real user ID, and the second is the resource limit on the number of queued signals for
566 | * this
567 | * process (see the description of RLIMIT_SIGPENDING in getrlimit(2)).
568 | * - SigPnd, ShdPnd: Number of signals pending for thread and for process as a whole (see
569 | * pthreads(7) and signal(7)).
570 | * - SigBlk, SigIgn, SigCgt: Masks indicating signals being blocked, ignored, and caught (see
571 | * signal(7)).
572 | * - CapInh, CapPrm, CapEff: Masks of capabilities enabled in inheritable, permitted, and
573 | * effective sets (see capabilities(7)).
574 | * - CapBnd: Capability Bounding set (since Linux 2.6.26, see capabilities(7)).
575 | * - Seccomp: Seccomp mode of the process (since Linux 3.8, see seccomp(2)). 0 means
576 | * SECCOMP_MODE_DISABLED; 1 means SECCOMP_MODE_STRICT; 2 means SECCOMP_MODE_FILTER. This field is
577 | * provided only if the kernel was built with the CONFIG_SECCOMP kernel configuration option
578 | * enabled.
579 | * - Cpus_allowed: Mask of CPUs on which this process may run (since Linux 2.6.24, see
580 | * cpuset(7)).
581 | * - Cpus_allowed_list: Same as previous, but in "list format" (since Linux 2.6.26, see
582 | * cpuset(7)).
583 | * - Mems_allowed: Mask of memory nodes allowed to this process (since Linux 2.6.24, see
584 | * cpuset(7)).
585 | * - Mems_allowed_list: Same as previous, but in "list format" (since Linux 2.6.26, see
586 | * cpuset(7)).
587 | * voluntary_ctxt_switches, nonvoluntary_ctxt_switches: Number of voluntary and involuntary
588 | * context
589 | * switches (since Linux 2.6.23).
590 | *
591 | *
592 | * @return the {@link Status} for this process
593 | * @throws IOException
594 | * if the file does not exist or we don't have read permissions.
595 | */
596 | public Status status() throws IOException {
597 | return Status.get(pid);
598 | }
599 |
600 | /**
601 | * The symbolic name corresponding to the location in the kernel where the process is sleeping.
602 | *
603 | * @return the contents of /proc/[pid]/wchan
604 | * @throws IOException
605 | * if the file does not exist or we don't have read permissions.
606 | */
607 | public String wchan() throws IOException {
608 | return read("wchan");
609 | }
610 |
611 | @Override public int describeContents() {
612 | return 0;
613 | }
614 |
615 | @Override public void writeToParcel(Parcel dest, int flags) {
616 | dest.writeString(this.name);
617 | dest.writeInt(this.pid);
618 | }
619 |
620 | protected AndroidProcess(Parcel in) {
621 | this.name = in.readString();
622 | this.pid = in.readInt();
623 | }
624 |
625 | public static final Creator CREATOR = new Creator() {
626 |
627 | @Override public AndroidProcess createFromParcel(Parcel source) {
628 | return new AndroidProcess(source);
629 | }
630 |
631 | @Override public AndroidProcess[] newArray(int size) {
632 | return new AndroidProcess[size];
633 | }
634 | };
635 |
636 | }
637 |
--------------------------------------------------------------------------------
/library/src/main/java/com/wenming/library/processutil/models/Cgroup.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015. Jared Rummler
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *
16 | */
17 |
18 | package com.wenming.library.processutil.models;
19 |
20 | import android.os.Parcel;
21 |
22 | import java.io.IOException;
23 | import java.util.ArrayList;
24 |
25 | /**
26 | * /proc/[pid]/cgroup (since Linux 2.6.24)
27 | *
28 | * This file describes control groups to which the process/task belongs. For each cgroup
29 | * hierarchy there is one entry containing colon-separated fields of the form:
30 | *
31 | * 5:cpuacct,cpu,cpuset:/daemons
32 | *
33 | * The colon-separated fields are, from left to right:
34 | *
35 | *
36 | * - hierarchy ID number
37 | * - set of subsystems bound to the hierarchy
38 | * - control group in the hierarchy to which the process belongs
39 | *
40 | *
41 | * This file is present only if the CONFIG_CGROUPS kernel configuration option is enabled.
42 | *
43 | * @see ControlGroup
44 | */
45 | public final class Cgroup extends ProcFile {
46 |
47 | /**
48 | * Read /proc/[pid]/cgroup.
49 | *
50 | * @param pid
51 | * the processes id.
52 | * @return the {@link Cgroup}
53 | * @throws IOException
54 | * if the file does not exist or we don't have read permissions.
55 | */
56 | public static Cgroup get(int pid) throws IOException {
57 | return new Cgroup(String.format("/proc/%d/cgroup", pid));
58 | }
59 |
60 | /** the process' control groups */
61 | public final ArrayList groups;
62 |
63 | private Cgroup(String path) throws IOException {
64 | super(path);
65 | String[] lines = content.split("\n");
66 | groups = new ArrayList<>();
67 | for (String line : lines) {
68 | try {
69 | groups.add(new ControlGroup(line));
70 | } catch (Exception ignored) {
71 | }
72 | }
73 | }
74 |
75 | private Cgroup(Parcel in) {
76 | super(in);
77 | this.groups = in.createTypedArrayList(ControlGroup.CREATOR);
78 | }
79 |
80 | public ControlGroup getGroup(String subsystem) {
81 | for (ControlGroup group : groups) {
82 | String[] systems = group.subsystems.split(",");
83 | for (String name : systems) {
84 | if (name.equals(subsystem)) {
85 | return group;
86 | }
87 | }
88 | }
89 | return null;
90 | }
91 |
92 | @Override public void writeToParcel(Parcel dest, int flags) {
93 | super.writeToParcel(dest, flags);
94 | dest.writeTypedList(groups);
95 | }
96 |
97 | public static final Creator CREATOR = new Creator() {
98 |
99 | @Override public Cgroup createFromParcel(Parcel source) {
100 | return new Cgroup(source);
101 | }
102 |
103 | @Override public Cgroup[] newArray(int size) {
104 | return new Cgroup[size];
105 | }
106 | };
107 |
108 | }
109 |
--------------------------------------------------------------------------------
/library/src/main/java/com/wenming/library/processutil/models/ControlGroup.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015. Jared Rummler
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *
16 | */
17 |
18 | package com.wenming.library.processutil.models;
19 |
20 | import android.os.Parcel;
21 | import android.os.Parcelable;
22 |
23 | public class ControlGroup implements Parcelable {
24 |
25 | /** hierarchy ID number */
26 | public final int id;
27 |
28 | /** set of subsystems bound to the hierarchy */
29 | public final String subsystems;
30 |
31 | /** control group in the hierarchy to which the process belongs */
32 | public final String group;
33 |
34 | protected ControlGroup(String line) throws NumberFormatException, IndexOutOfBoundsException {
35 | String[] fields = line.split(":");
36 | id = Integer.parseInt(fields[0]);
37 | subsystems = fields[1];
38 | group = fields[2];
39 | }
40 |
41 | protected ControlGroup(Parcel in) {
42 | this.id = in.readInt();
43 | this.subsystems = in.readString();
44 | this.group = in.readString();
45 | }
46 |
47 | @Override public int describeContents() {
48 | return 0;
49 | }
50 |
51 | @Override public void writeToParcel(Parcel dest, int flags) {
52 | dest.writeInt(this.id);
53 | dest.writeString(this.subsystems);
54 | dest.writeString(this.group);
55 | }
56 |
57 | @Override public String toString() {
58 | return String.format("%d:%s:%s", id, subsystems, group);
59 | }
60 |
61 | public static final Creator CREATOR = new Creator() {
62 |
63 | @Override public ControlGroup createFromParcel(Parcel source) {
64 | return new ControlGroup(source);
65 | }
66 |
67 | @Override public ControlGroup[] newArray(int size) {
68 | return new ControlGroup[size];
69 | }
70 | };
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/library/src/main/java/com/wenming/library/processutil/models/ProcFile.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015. Jared Rummler
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *
16 | */
17 |
18 | package com.wenming.library.processutil.models;
19 |
20 | import android.os.Parcel;
21 | import android.os.Parcelable;
22 |
23 | import java.io.BufferedReader;
24 | import java.io.File;
25 | import java.io.FileReader;
26 | import java.io.IOException;
27 |
28 | public class ProcFile extends File implements Parcelable {
29 |
30 | /**
31 | * Read the contents of a file.
32 | *
33 | * @param path
34 | * the absolute path to the file.
35 | * @return the contents of the file.
36 | * @throws IOException
37 | * if an error occurred while reading.
38 | */
39 | protected static String readFile(String path) throws IOException {
40 | BufferedReader reader = null;
41 | try {
42 | StringBuilder output = new StringBuilder();
43 | reader = new BufferedReader(new FileReader(path));
44 | for (String line = reader.readLine(), newLine = ""; line != null; line = reader.readLine()) {
45 | output.append(newLine).append(line);
46 | newLine = "\n";
47 | }
48 | return output.toString();
49 | } finally {
50 | if (reader != null) {
51 | reader.close();
52 | }
53 | }
54 | }
55 |
56 | public final String content;
57 |
58 | protected ProcFile(String path) throws IOException {
59 | super(path);
60 | content = readFile(path);
61 | }
62 |
63 | protected ProcFile(Parcel in) {
64 | super(in.readString());
65 | this.content = in.readString();
66 | }
67 |
68 | @Override public long length() {
69 | return content.length();
70 | }
71 |
72 | @Override public int describeContents() {
73 | return 0;
74 | }
75 |
76 | @Override public void writeToParcel(Parcel dest, int flags) {
77 | dest.writeString(getAbsolutePath());
78 | dest.writeString(this.content);
79 | }
80 |
81 | public static final Creator CREATOR = new Creator() {
82 |
83 | @Override public ProcFile createFromParcel(Parcel in) {
84 | return new ProcFile(in);
85 | }
86 |
87 | @Override public ProcFile[] newArray(int size) {
88 | return new ProcFile[size];
89 | }
90 | };
91 |
92 | }
93 |
--------------------------------------------------------------------------------
/library/src/main/java/com/wenming/library/processutil/models/Stat.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015. Jared Rummler
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *
16 | */
17 |
18 | package com.wenming.library.processutil.models;
19 |
20 | import android.os.Parcel;
21 | import android.os.Parcelable;
22 |
23 | import java.io.IOException;
24 |
25 | /**
26 | * /proc/[pid]/stat
27 | *
28 | * Status information about the process. This is used by ps(1). It is defined in the kernel
29 | * source file fs/proc/array.c.
30 | *
31 | * The fields, in order, with their proper scanf(3) format specifiers, are:
32 | *
33 | *
34 | * - pid %d The process ID.
35 | * - comm %s The filename of the executable, in parentheses. This is visible whether or not
36 | * the executable is swapped out.
37 | * - state %c One of the following characters, indicating process state:
38 | *
39 | * - R Running
40 | * - S Sleeping in an interruptible wait
41 | * - D Waiting in uninterruptible disk sleep
42 | * - Z Zombie
43 | * - T Stopped (on a signal) or (before Linux 2.6.33) trace stopped
44 | * - t Tracing stop (Linux 2.6.33 onward)
45 | * - W Paging (only before Linux 2.6.0)
46 | * - X Dead (from Linux 2.6.0 onward)
47 | * - x Dead (Linux 2.6.33 to 3.13 only)
48 | * - K Wakekill (Linux 2.6.33 to 3.13 only)
49 | * - W Waking (Linux 2.6.33 to 3.13 only)
50 | * - P Parked (Linux 3.9 to 3.13 only)
51 | *
52 | *
53 | * - ppid %d The PID of the parent of this process.
54 | * - pgrp %d The process group ID of the process.
55 | * - session %d The session ID of the process.
56 | * - tty_nr %d The controlling terminal of the process. (The minor device number is contained
57 | * in the combination of bits 31 to 20 and 7 to 0; the major device number is in bits 15 to 8.)
58 | *
59 | * - tpgid %d The ID of the foreground process group of the controlling terminal of the
60 | * process.
61 | * - flags %u The kernel flags word of the process. For bit meanings, see the PF_* defines in
62 | * the Linux kernel source file include/linux/sched.h. Details depend on the kernel version.
63 | * The format for this field was %lu before Linux 2.6.
64 | * - minflt %lu The number of minor faults the process has made which have not required
65 | * loading a memory page from disk.
66 | * - cminflt %lu The number of minor faults that the process's waited-for children have
67 | * made
68 | * - majflt %lu The number of major faults the process has made which have required loading a
69 | * memory page from disk.
70 | * - cmajflt %lu The number of major faults that the process's waited-for children have
71 | * made
72 | * - utime %lu Amount of time that this process has been scheduled in user mode, measured in
73 | * clock ticks (divide by sysconf(_SC_CLK_TCK)). This includes guest time, guest_time (time
74 | * spent running a virtual CPU, see below), so that applications that are not aware of the guest
75 | * time field do not lose that time from their calculations.
76 | * - stime %lu Amount of time that this process has been scheduled in kernel mode, measured
77 | * in clock ticks (divide by sysconf(_SC_CLK_TCK)).
78 | * - cutime %ld Amount of time that this process's waited-for children have been scheduled in
79 | * user mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK)). (See also times(2).)
80 | * This includes guest time, cguest_time (time spent running a virtual CPU, see below).
81 | * - cstime %ld Amount of time that this process's waited-for children have been scheduled in
82 | * kernel mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK)).
83 | * - priority %ld (Explanation for Linux 2.6) For processes running a real-time scheduling
84 | * policy (policy below; see sched_setscheduler(2)), this is the negated scheduling priority,
85 | * minus one; that is, a number in the range -2 to -100, corresponding to real-time priorities 1
86 | * to 99. For processes running under a non-real-time scheduling policy, this is the raw nice
87 | * value (setpriority(2)) as represented in the kernel. The kernel stores nice values as numbers
88 | * in the range 0 (high) to 39 (low), corresponding to the user-visible nice range of -20 to 19.
89 | * Before Linux 2.6, this was a scaled value based on the scheduler weighting given to this
90 | * process
91 | * - nice %ld The nice value (see setpriority(2)), a value in the range 19 (low priority) to
92 | * -20 (high priority).
93 | * - num_threads %ld Number of threads in this process (since Linux 2.6). Before kernel 2.6,
94 | * this field was hard coded to 0 as a placeholder for an earlier removed field.
95 | * - itrealvalue %ld The time in jiffies before the next SIGALRM is sent to the process due
96 | * to an interval timer. Since kernel 2.6.17, this field is no longer maintained, and is hard
97 | * coded as 0.
98 | * - starttime %llu The time the process started after system boot. In kernels before Linux
99 | * 2.6, this value was expressed in jiffies. Since Linux 2.6, the value is expressed in clock
100 | * ticks (divide by sysconf(_SC_CLK_TCK)).
101 | * - The format for this field was %lu before Linux 2.6. (23) vsize %lu Virtual memory size
102 | * in bytes.
103 | * - rss %ld Resident Set Size: number of pages the process has in real memory. This is just
104 | * the pages which count toward text, data, or stack space. This does not include pages which
105 | * have not been demand-loaded in, or which are swapped out.
106 | * - rsslim %lu Current soft limit in bytes on the rss of the process; see the description of
107 | * RLIMIT_RSS in getrlimit(2).
108 | * - startcode %lu The address above which program text can run.
109 | * - endcode %lu The address below which program text can run.
110 | * - startstack %lu The address of the start (i.e., bottom) of the stack.
111 | * - kstkesp %lu The current value of ESP (stack pointer), as found in the kernel stack page
112 | * for the process.
113 | * - kstkeip %lu The current EIP (instruction pointer).
114 | * - signal %lu The bitmap of pending signals, displayed as a decimal number. Obsolete,
115 | * because it does not provide information on real-time signals; use /proc/[pid]/status
116 | * instead
117 | * - blocked %lu The bitmap of blocked signals, displayed as a decimal number. Obsolete,
118 | * because it does not provide information on real-time signals; use /proc/[pid]/status
119 | * instead
120 | * - sigignore %lu The bitmap of ignored signals, displayed as a decimal number. Obsolete,
121 | * because it does not provide information on real-time signals; use /proc/[pid]/status
122 | * instead
123 | * - sigcatch %lu The bitmap of caught signals, displayed as a decimal number. Obsolete,
124 | * because it does not provide information on real-time signals; use /proc/[pid]/status
125 | * instead.
126 | * - wchan %lu This is the "channel" in which the process is waiting. It is the address of a
127 | * location in the kernel where the process is sleeping. The corresponding symbolic name can be
128 | * found in /proc/[pid]/wchan.
129 | * - nswap %lu Number of pages swapped (not maintained).
130 | * - cnswap %lu Cumulative nswap for child processes (not maintained).
131 | * - exit_signal %d (since Linux 2.1.22) Signal to be sent to parent when we die.
132 | * - processor %d (since Linux 2.2.8) CPU number last executed on.
133 | * - rt_priority %u (since Linux 2.5.19) Real-time scheduling priority, a number in the
134 | * range 1 to 99 for processes scheduled under a real-time policy, or 0, for non-real-time
135 | * processes (see sched_setscheduler(2)).
136 | * - policy %u (since Linux 2.5.19) Scheduling policy (see sched_setscheduler(2)). Decode
137 | * using the SCHED_* constants in linux/sched.h. The format for this field was %lu before Linux
138 | * 2.6.22.
139 | * - delayacct_blkio_ticks %llu (since Linux 2.6.18) Aggregated block I/O delays, measured
140 | * in clock ticks (centiseconds).
141 | * - guest_time %lu (since Linux 2.6.24) Guest time of the process (time spent running a
142 | * virtual CPU for a guest operating system), measured in clock ticks (divide by
143 | * sysconf(_SC_CLK_TCK)).
144 | * - cguest_time %ld (since Linux 2.6.24) Guest time of the process's children, measured in
145 | * clock ticks (divide by sysconf(_SC_CLK_TCK)).
146 | * - start_data %lu (since Linux 3.3) Address above which program initialized and
147 | * uninitialized (BSS) data are placed.
148 | * - end_data %lu (since Linux 3.3) Address below which program initialized and
149 | * uninitialized (BSS) data are placed.
150 | * - start_brk %lu (since Linux 3.3) Address above which program heap can be expanded with
151 | * brk(2).
152 | * - arg_start %lu (since Linux 3.5) Address above which program command-line arguments
153 | * (argv) are placed.
154 | * - arg_end %lu (since Linux 3.5) Address below program command-line arguments (argv) are
155 | * placed.
156 | * - env_start %lu (since Linux 3.5) Address above which program environment is placed.
157 | * - env_end %lu (since Linux 3.5) Address below which program environment is placed.
158 | * - exit_code %d (since Linux 3.5) The thread's exit status in the form reported by
159 | * waitpid(2).
160 | *
161 | */
162 | public final class Stat extends ProcFile {
163 |
164 | /**
165 | * Read /proc/[pid]/stat.
166 | *
167 | * @param pid
168 | * the process id.
169 | * @return the {@link Stat}
170 | * @throws IOException
171 | * if the file does not exist or we don't have read permissions.
172 | */
173 | public static Stat get(int pid) throws IOException {
174 | return new Stat(String.format("/proc/%d/stat", pid));
175 | }
176 |
177 | private final String[] fields;
178 |
179 | private Stat(String path) throws IOException {
180 | super(path);
181 | fields = content.split("\\s+");
182 | }
183 |
184 | private Stat(Parcel in) {
185 | super(in);
186 | this.fields = in.createStringArray();
187 | }
188 |
189 | /** The process ID. */
190 | public int getPid() {
191 | return Integer.parseInt(fields[0]);
192 | }
193 |
194 | /**
195 | * The filename of the executable, in parentheses. This is visible whether or not the
196 | * executable is swapped out.
197 | */
198 | public String getComm() {
199 | return fields[1].replace("(", "").replace(")", "");
200 | }
201 |
202 | /**
203 | * One of the following characters, indicating process state:
204 | *
205 | *
206 | * - 'R' Running
207 | * - 'S' Sleeping in an interruptible wait
208 | * - 'D' Waiting in uninterruptible disk sleep
209 | * - 'Z' Zombie
210 | * - 'T' Stopped (on a signal) or (before Linux 2.6.33) trace stopped
211 | * - 't' Tracing stop (Linux 2.6.33 onward)
212 | * - 'W' Paging (only before Linux 2.6.0)
213 | * - 'X' Dead (from Linux 2.6.0 onward)
214 | * - 'x' Dead (Linux 2.6.33 to 3.13 only)
215 | * - 'K' Wakekill (Linux 2.6.33 to 3.13 only)
216 | * - 'W' Waking (Linux 2.6.33 to 3.13 only)
217 | * - 'P' Parked (Linux 3.9 to 3.13 only)
218 | *
219 | */
220 | public char state() {
221 | return fields[2].charAt(0);
222 | }
223 |
224 | /**
225 | * The PID of the parent of this process.
226 | */
227 | public int ppid() {
228 | return Integer.parseInt(fields[3]);
229 | }
230 |
231 | /**
232 | * The process group ID of the process.
233 | */
234 | public int pgrp() {
235 | return Integer.parseInt(fields[4]);
236 | }
237 |
238 | /**
239 | * The session ID of the process.
240 | */
241 | public int session() {
242 | return Integer.parseInt(fields[5]);
243 | }
244 |
245 | /**
246 | * The controlling terminal of the process. (The minor device number is contained in the
247 | * combination of bits 31 to 20 and 7 to 0; the major device number is in bits 15 to 8.)
248 | */
249 | public int tty_nr() {
250 | return Integer.parseInt(fields[6]);
251 | }
252 |
253 | /**
254 | * The ID of the foreground process group of the controlling terminal of the process.
255 | */
256 | public int tpgid() {
257 | return Integer.parseInt(fields[7]);
258 | }
259 |
260 | /**
261 | * The kernel flags word of the process. For bit meanings, see the PF_* defines in the Linux
262 | * kernel source file include/linux/sched.h. Details depend on the kernel version.
263 | *
264 | * The format for this field was %lu before Linux 2.6.
265 | */
266 | public int flags() {
267 | return Integer.parseInt(fields[8]);
268 | }
269 |
270 | /**
271 | * The number of minor faults the process has made which have not required loading a memory
272 | * page from disk.
273 | */
274 | public long minflt() {
275 | return Long.parseLong(fields[9]);
276 | }
277 |
278 | /**
279 | * The number of minor faults that the process's waited-for children have made.
280 | */
281 | public long cminflt() {
282 | return Long.parseLong(fields[10]);
283 | }
284 |
285 | /**
286 | * The number of major faults the process has made which have required loading a memory page
287 | * from disk.
288 | */
289 | public long majflt() {
290 | return Long.parseLong(fields[11]);
291 | }
292 |
293 | /**
294 | * The number of major faults that the process's waited-for children have made.
295 | */
296 | public long cmajflt() {
297 | return Long.parseLong(fields[12]);
298 | }
299 |
300 | /**
301 | * Amount of time that this process has been scheduled in user mode, measured in clock ticks
302 | * (divide by sysconf(_SC_CLK_TCK)). This includes guest time, guest_time (time spent running
303 | * a virtual CPU, see below), so that applications that are not aware of the guest time field
304 | * do not lose that time from their calculations.
305 | */
306 | public long utime() {
307 | return Long.parseLong(fields[13]);
308 | }
309 |
310 | /**
311 | * Amount of time that this process has been scheduled in kernel mode, measured in clock ticks
312 | * (divide by sysconf(_SC_CLK_TCK)).
313 | */
314 | public long stime() {
315 | return Long.parseLong(fields[14]);
316 | }
317 |
318 | /**
319 | * Amount of time that this process's waited-for children have been scheduled in user mode,
320 | * measured in clock ticks (divide by sysconf(_SC_CLK_TCK)). (See also times(2).) This
321 | * includes guest time, cguest_time (time spent running a virtual CPU, see below).
322 | */
323 | public long cutime() {
324 | return Long.parseLong(fields[15]);
325 | }
326 |
327 | /**
328 | * Amount of time that this process's waited-for children have been scheduled in kernel mode,
329 | * measured in clock ticks (divide by sysconf(_SC_CLK_TCK)).
330 | */
331 | public long cstime() {
332 | return Long.parseLong(fields[16]);
333 | }
334 |
335 | /**
336 | * (Explanation for Linux 2.6) For processes running a real-time scheduling policy (policy
337 | * below; see sched_setscheduler(2)), this is the negated scheduling priority, minus one; that
338 | * is,
339 | * a number in the range -2 to -100, corresponding to real-time priorities 1 to 99. For
340 | * processes
341 | * running under a non-real-time scheduling policy, this is the raw nice value (setpriority(2))
342 | * as
343 | * represented in the kernel. The kernel stores nice values as numbers in the range 0 (high) to
344 | * 39 (low), corresponding to the user-visible nice range of -20 to 19.
345 | *
346 | * Before Linux 2.6, this was a scaled value based on the scheduler weighting given to this
347 | * process.
348 | */
349 | public long priority() {
350 | return Long.parseLong(fields[17]);
351 | }
352 |
353 | /**
354 | * The nice value (see setpriority(2)), a value in the range 19 (low priority) to -20 (high
355 | * priority).
356 | */
357 | public int nice() {
358 | return Integer.parseInt(fields[18]);
359 | }
360 |
361 | /**
362 | * Number of threads in this process (since Linux 2.6). Before kernel 2.6, this field was hard
363 | * coded to 0 as a placeholder for an earlier removed field.
364 | */
365 | public long num_threads() {
366 | return Long.parseLong(fields[19]);
367 | }
368 |
369 | /**
370 | * The time in jiffies before the next SIGALRM is sent to the process due to an interval timer.
371 | * Since kernel 2.6.17, this field is no longer maintained, and is hard coded as 0.
372 | */
373 | public long itrealvalue() {
374 | return Long.parseLong(fields[20]);
375 | }
376 |
377 | /**
378 | * The time the process started after system boot. In kernels before Linux 2.6, this value was
379 | * expressed in jiffies. Since Linux 2.6, the value is expressed in clock ticks (divide by
380 | * sysconf(_SC_CLK_TCK)).
381 | *
382 | * The format for this field was %lu before Linux 2.6.
383 | */
384 | public long starttime() {
385 | return Long.parseLong(fields[21]);
386 | }
387 |
388 | /**
389 | * Virtual memory size in bytes.
390 | */
391 | public long vsize() {
392 | return Long.parseLong(fields[22]);
393 | }
394 |
395 | /**
396 | * Resident Set Size: number of pages the process has in real memory. This is just the pages
397 | * which count toward text, data, or stack space. This does not include pages which have not
398 | * been demand-loaded in, or which are swapped out.
399 | */
400 | public long rss() {
401 | return Long.parseLong(fields[23]);
402 | }
403 |
404 | /**
405 | * Current soft limit in bytes on the rss of the process; see the description of RLIMIT_RSS in
406 | * getrlimit(2).
407 | */
408 | public long rsslim() {
409 | return Long.parseLong(fields[24]);
410 | }
411 |
412 | /**
413 | * The address above which program text can run.
414 | */
415 | public long startcode() {
416 | return Long.parseLong(fields[25]);
417 | }
418 |
419 | /**
420 | * The address below which program text can run.
421 | */
422 | public long endcode() {
423 | return Long.parseLong(fields[26]);
424 | }
425 |
426 | /**
427 | * The address of the start (i.e., bottom) of the stack.
428 | */
429 | public long startstack() {
430 | return Long.parseLong(fields[27]);
431 | }
432 |
433 | /**
434 | * The current value of ESP (stack pointer), as found in the kernel stack page for the process.
435 | */
436 | public long kstkesp() {
437 | return Long.parseLong(fields[28]);
438 | }
439 |
440 | /**
441 | * The current EIP (instruction pointer).
442 | */
443 | public long kstkeip() {
444 | return Long.parseLong(fields[29]);
445 | }
446 |
447 | /**
448 | * The bitmap of pending signals, displayed as a decimal number. Obsolete, because it does not
449 | * provide information on real-time signals; use /proc/[pid]/status instead.
450 | */
451 | public long signal() {
452 | return Long.parseLong(fields[30]);
453 | }
454 |
455 | /**
456 | * The bitmap of blocked signals, displayed as a decimal number. Obsolete, because it does not
457 | * provide information on real-time signals; use /proc/[pid]/status instead.
458 | */
459 | public long blocked() {
460 | return Long.parseLong(fields[31]);
461 | }
462 |
463 | /**
464 | * The bitmap of ignored signals, displayed as a decimal number. Obsolete, because it does not
465 | * provide information on real-time signals; use /proc/[pid]/status instead.
466 | */
467 | public long sigignore() {
468 | return Long.parseLong(fields[32]);
469 | }
470 |
471 | /**
472 | * The bitmap of caught signals, displayed as a decimal number. Obsolete, because it does not
473 | * provide information on real-time signals; use /proc/[pid]/status instead.
474 | */
475 | public long sigcatch() {
476 | return Long.parseLong(fields[33]);
477 | }
478 |
479 | /**
480 | * This is the "channel" in which the process is waiting. It is the address of a location in the
481 | * kernel where the process is sleeping. The corresponding symbolic name can be found in
482 | * /proc/[pid]/wchan.
483 | */
484 | public long wchan() {
485 | return Long.parseLong(fields[34]);
486 | }
487 |
488 | /**
489 | * Number of pages swapped (not maintained).
490 | */
491 | public long nswap() {
492 | return Long.parseLong(fields[35]);
493 | }
494 |
495 | /**
496 | * Cumulative nswap for child processes (not maintained).
497 | */
498 | public long cnswap() {
499 | return Long.parseLong(fields[36]);
500 | }
501 |
502 | /**
503 | * (since Linux 2.1.22)
504 | * Signal to be sent to parent when we die.
505 | */
506 | public int exit_signal() {
507 | return Integer.parseInt(fields[37]);
508 | }
509 |
510 | /**
511 | * (since Linux 2.2.8)
512 | * CPU number last executed on.
513 | */
514 | public int processor() {
515 | return Integer.parseInt(fields[38]);
516 | }
517 |
518 | /**
519 | * (since Linux 2.5.19)
520 | * Real-time scheduling priority, a number in the range 1 to 99 for processes scheduled under a
521 | * real-time policy, or 0, for non-real-time processes (see sched_setscheduler(2)).
522 | */
523 | public int rt_priority() {
524 | return Integer.parseInt(fields[39]);
525 | }
526 |
527 | /**
528 | * (since Linux 2.5.19) Scheduling policy (see sched_setscheduler(2)). Decode using the
529 | * SCHED_*
530 | * constants in linux/sched.h.
531 | *
532 | * The format for this field was %lu before Linux 2.6.22.
533 | */
534 | public int policy() {
535 | return Integer.parseInt(fields[40]);
536 | }
537 |
538 | /**
539 | * (since Linux 2.6.18)
540 | * Aggregated block I/O delays, measured in clock ticks (centiseconds).
541 | */
542 | public long delayacct_blkio_ticks() {
543 | return Long.parseLong(fields[41]);
544 | }
545 |
546 | /**
547 | * (since Linux 2.6.24)
548 | * Guest time of the process (time spent running a virtual CPU for a guest operating system),
549 | * measured in clock ticks (divide by sysconf(_SC_CLK_TCK)).
550 | */
551 | public long guest_time() {
552 | return Long.parseLong(fields[42]);
553 | }
554 |
555 | /**
556 | * (since Linux 2.6.24)
557 | * Guest time of the process's children, measured in clock ticks (divide by
558 | * sysconf(_SC_CLK_TCK)).
559 | */
560 | public long cguest_time() {
561 | return Long.parseLong(fields[43]);
562 | }
563 |
564 | /**
565 | * (since Linux 3.3)
566 | * Address above which program initialized and uninitialized (BSS) data are placed.
567 | */
568 | public long start_data() {
569 | return Long.parseLong(fields[44]);
570 | }
571 |
572 | /**
573 | * (since Linux 3.3)
574 | * Address below which program initialized and uninitialized (BSS) data are placed.
575 | */
576 | public long end_data() {
577 | return Long.parseLong(fields[45]);
578 | }
579 |
580 | /**
581 | * (since Linux 3.3)
582 | * Address above which program heap can be expanded with brk(2).
583 | */
584 | public long start_brk() {
585 | return Long.parseLong(fields[46]);
586 | }
587 |
588 | /**
589 | * (since Linux 3.5)
590 | * Address above which program command-line arguments (argv) are placed.
591 | */
592 | public long arg_start() {
593 | return Long.parseLong(fields[47]);
594 | }
595 |
596 | /**
597 | * (since Linux 3.5)
598 | * Address below program command-line arguments (argv) are placed.
599 | */
600 | public long arg_end() {
601 | return Long.parseLong(fields[48]);
602 | }
603 |
604 | /**
605 | * (since Linux 3.5)
606 | * Address above which program environment is placed.
607 | */
608 | public long env_start() {
609 | return Long.parseLong(fields[49]);
610 | }
611 |
612 | /**
613 | * (since Linux 3.5)
614 | * Address below which program environment is placed.
615 | */
616 | public long env_end() {
617 | return Long.parseLong(fields[50]);
618 | }
619 |
620 | /**
621 | * (since Linux 3.5)
622 | * The thread's exit status in the form reported by waitpid(2).
623 | */
624 | public int exit_code() {
625 | return Integer.parseInt(fields[51]);
626 | }
627 |
628 | @Override public void writeToParcel(Parcel dest, int flags) {
629 | super.writeToParcel(dest, flags);
630 | dest.writeStringArray(fields);
631 | }
632 |
633 | public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
634 |
635 | @Override public Stat createFromParcel(Parcel source) {
636 | return new Stat(source);
637 | }
638 |
639 | @Override public Stat[] newArray(int size) {
640 | return new Stat[size];
641 | }
642 | };
643 |
644 | }
645 |
--------------------------------------------------------------------------------
/library/src/main/java/com/wenming/library/processutil/models/Statm.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015. Jared Rummler
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *
16 | */
17 |
18 | package com.wenming.library.processutil.models;
19 |
20 | import android.os.Parcel;
21 | import android.os.Parcelable;
22 |
23 | import java.io.IOException;
24 |
25 | /**
26 | * Provides information about memory usage, measured in pages.
27 | *
28 | * The columns are:
29 | *
30 | *
31 | * - size (1) total program size (same as VmSize in /proc/[pid]/status)
32 | * - resident (2) resident set size (same as VmRSS in /proc/[pid]/status)
33 | * - share (3) shared pages (i.e., backed by a file)
34 | * - text (4) text (code)
35 | * - lib (5) library (unused in Linux 2.6)
36 | * - data (6) data + stack
37 | * - dt (7) dirty pages (unused in Linux 2.6)
38 | *
39 | */
40 | public final class Statm extends ProcFile {
41 |
42 | /**
43 | * Read /proc/[pid]/statm.
44 | *
45 | * @param pid
46 | * the process id.
47 | * @return the {@link Statm}
48 | * @throws IOException
49 | * if the file does not exist or we don't have read permissions.
50 | */
51 | public static Statm get(int pid) throws IOException {
52 | return new Statm(String.format("/proc/%d/statm", pid));
53 | }
54 |
55 | public final String[] fields;
56 |
57 | private Statm(String path) throws IOException {
58 | super(path);
59 | fields = content.split("\\s+");
60 | }
61 |
62 | private Statm(Parcel in) {
63 | super(in);
64 | this.fields = in.createStringArray();
65 | }
66 |
67 | /**
68 | * @return the total program size in bytes
69 | */
70 | public long getSize() {
71 | return Long.parseLong(fields[0]) * 1024;
72 | }
73 |
74 | /**
75 | * @return the resident set size in bytes
76 | */
77 | public long getResidentSetSize() {
78 | return Long.parseLong(fields[1]) * 1024;
79 | }
80 |
81 | @Override public void writeToParcel(Parcel dest, int flags) {
82 | super.writeToParcel(dest, flags);
83 | dest.writeStringArray(this.fields);
84 | }
85 |
86 | public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
87 |
88 | @Override public Statm createFromParcel(Parcel source) {
89 | return new Statm(source);
90 | }
91 |
92 | @Override public Statm[] newArray(int size) {
93 | return new Statm[size];
94 | }
95 | };
96 |
97 | }
98 |
--------------------------------------------------------------------------------
/library/src/main/java/com/wenming/library/processutil/models/Status.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2015. Jared Rummler
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | *
16 | */
17 |
18 | package com.wenming.library.processutil.models;
19 |
20 | import android.os.Parcel;
21 |
22 | import java.io.IOException;
23 |
24 | /**
25 | * /proc/[pid]/status
26 | *
27 | * Provides much of the information in /proc/[pid]/stat and /proc/[pid]/statm in a format that's
28 | * easier for humans to parse.
29 | *
30 | * Here's an example:
31 | *
32 | *
33 | * $ cat /proc/$$/status
34 | * Name: bash
35 | * State: S (sleeping)
36 | * Tgid: 3515
37 | * Pid: 3515
38 | * PPid: 3452
39 | * TracerPid: 0
40 | * Uid: 1000 1000 1000 1000
41 | * Gid: 100 100 100 100
42 | * FDSize: 256
43 | * Groups: 16 33 100
44 | * VmPeak: 9136 kB
45 | * VmSize: 7896 kB
46 | * VmLck: 0 kB
47 | * VmPin: 0 kB
48 | * VmHWM: 7572 kB
49 | * VmRSS: 6316 kB
50 | * VmData: 5224 kB
51 | * VmStk: 88 kB
52 | * VmExe: 572 kB
53 | * VmLib: 1708 kB
54 | * VmPMD: 4 kB
55 | * VmPTE: 20 kB
56 | * VmSwap: 0 kB
57 | * Threads: 1
58 | * SigQ: 0/3067
59 | * SigPnd: 0000000000000000
60 | * ShdPnd: 0000000000000000
61 | * SigBlk: 0000000000010000
62 | * SigIgn: 0000000000384004
63 | * SigCgt: 000000004b813efb
64 | * CapInh: 0000000000000000
65 | * CapPrm: 0000000000000000
66 | * CapEff: 0000000000000000
67 | * CapBnd: ffffffffffffffff
68 | * Seccomp: 0
69 | * Cpus_allowed: 00000001
70 | * Cpus_allowed_list: 0
71 | * Mems_allowed: 1
72 | * Mems_allowed_list: 0
73 | * voluntary_ctxt_switches: 150
74 | * nonvoluntary_ctxt_switches: 545
75 | *
76 | *
77 | * The fields are as follows:
78 | *
79 | *
80 | * - Name: Command run by this process.
81 | * - State: Current state of the process. One of "R (running)", "S (sleeping)", "D (disk
82 | * sleep)",
83 | * "T (stopped)", "T (tracing stop)", "Z (zombie)", or "X (dead)".
84 | * - Tgid: Thread group ID (i.e., Process ID).
85 | * - Pid: Thread ID (see gettid(2)).
86 | * - PPid: PID of parent process.
87 | * - TracerPid: PID of process tracing this process (0 if not being traced).
88 | * - Uid, Gid: Real, effective, saved set, and filesystem UIDs (GIDs).
89 | * - FDSize: Number of file descriptor slots currently allocated.
90 | * - Groups: Supplementary group list.
91 | * - VmPeak: Peak virtual memory size.
92 | * - VmSize: Virtual memory size.
93 | * - VmLck: Locked memory size (see mlock(3)).
94 | * - VmPin: Pinned memory size (since Linux 3.2). These are pages that can't be moved because
95 | * something needs to directly access physical memory.
96 | * - VmHWM: Peak resident set size ("high water mark").
97 | * - VmRSS: Resident set size.
98 | * - VmData, VmStk, VmExe: Size of data, stack, and text segments.
99 | * - VmLib: Shared library code size.
100 | * - VmPTE: Page table entries size (since Linux 2.6.10).
101 | * - VmPMD: Size of second-level page tables (since Linux 4.0).
102 | * - VmSwap: Swapped-out virtual memory size by anonymous private pages; shmem swap usage is not
103 | * included (since Linux 2.6.34).
104 | * - Threads: Number of threads in process containing this thread.
105 | * - SigQ: This field contains two slash-separated numbers that relate to queued signals for the
106 | * real user ID of this process. The first of these is the number of currently queued signals for
107 | * this real user ID, and the second is the resource limit on the number of queued signals for this
108 | * process (see the description of RLIMIT_SIGPENDING in getrlimit(2)).
109 | * - SigPnd, ShdPnd: Number of signals pending for thread and for process as a whole (see
110 | * pthreads(7) and signal(7)).
111 | * - SigBlk, SigIgn, SigCgt: Masks indicating signals being blocked, ignored, and caught (see
112 | * signal(7)).
113 | * - CapInh, CapPrm, CapEff: Masks of capabilities enabled in inheritable, permitted, and
114 | * effective sets (see capabilities(7)).
115 | * - CapBnd: Capability Bounding set (since Linux 2.6.26, see capabilities(7)).
116 | * - Seccomp: Seccomp mode of the process (since Linux 3.8, see seccomp(2)). 0 means
117 | * SECCOMP_MODE_DISABLED; 1 means SECCOMP_MODE_STRICT; 2 means SECCOMP_MODE_FILTER. This field is
118 | * provided only if the kernel was built with the CONFIG_SECCOMP kernel configuration option
119 | * enabled.
120 | * - Cpus_allowed: Mask of CPUs on which this process may run (since Linux 2.6.24, see
121 | * cpuset(7)).
122 | * - Cpus_allowed_list: Same as previous, but in "list format" (since Linux 2.6.26, see
123 | * cpuset(7)).
124 | * - Mems_allowed: Mask of memory nodes allowed to this process (since Linux 2.6.24, see
125 | * cpuset(7)).
126 | * - Mems_allowed_list: Same as previous, but in "list format" (since Linux 2.6.26, see
127 | * cpuset(7)).
128 | * voluntary_ctxt_switches, nonvoluntary_ctxt_switches: Number of voluntary and involuntary context
129 | * switches (since Linux 2.6.23).
130 | *
131 | */
132 | public final class Status extends ProcFile {
133 |
134 | /**
135 | * Read /proc/[pid]/status.
136 | *
137 | * @param pid
138 | * the process id.
139 | * @return the {@link Status}
140 | * @throws IOException
141 | * if the file does not exist or we don't have read permissions.
142 | */
143 | public static Status get(int pid) throws IOException {
144 | return new Status(String.format("/proc/%d/status", pid));
145 | }
146 |
147 | private Status(String path) throws IOException {
148 | super(path);
149 | }
150 |
151 | private Status(Parcel in) {
152 | super(in);
153 | }
154 |
155 | /**
156 | * Get the value of one of the fields.
157 | *
158 | * @param fieldName
159 | * the field name. E.g "PPid", "Uid", "Groups".
160 | * @return The value of the field or {@code null}.
161 | */
162 | public String getValue(String fieldName) {
163 | String[] lines = content.split("\n");
164 | for (String line : lines) {
165 | if (line.startsWith(fieldName + ":")) {
166 | return line.split(fieldName + ":")[1].trim();
167 | }
168 | }
169 | return null;
170 | }
171 |
172 | /**
173 | * @return The process' UID or -1 if parsing the UID failed.
174 | */
175 | public int getUid() {
176 | try {
177 | return Integer.parseInt(getValue("Uid").split("\\s+")[0]);
178 | } catch (Exception e) {
179 | return -1;
180 | }
181 | }
182 |
183 | /**
184 | * @return The process' GID or -1 if parsing the GID failed.
185 | */
186 | public int getGid() {
187 | try {
188 | return Integer.parseInt(getValue("Gid").split("\\s+")[0]);
189 | } catch (Exception e) {
190 | return -1;
191 | }
192 | }
193 |
194 | public static final Creator CREATOR = new Creator() {
195 |
196 | @Override public Status createFromParcel(Parcel source) {
197 | return new Status(source);
198 | }
199 |
200 | @Override public Status[] newArray(int size) {
201 | return new Status[size];
202 | }
203 | };
204 |
205 | }
206 |
--------------------------------------------------------------------------------
/library/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Library
3 | 请为App打开辅助功能开关!!
4 |
5 |
--------------------------------------------------------------------------------
/library/src/main/res/xml/detection_service_config.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/library/src/test/java/com/wenming/library/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.wenming.library;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/sample/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/sample/1.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wenmingvs/AndroidProcess/0c05dd14279cc3dc32baffdbb94e76d5ead56f33/sample/1.PNG
--------------------------------------------------------------------------------
/sample/2.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wenmingvs/AndroidProcess/0c05dd14279cc3dc32baffdbb94e76d5ead56f33/sample/2.PNG
--------------------------------------------------------------------------------
/sample/3.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wenmingvs/AndroidProcess/0c05dd14279cc3dc32baffdbb94e76d5ead56f33/sample/3.PNG
--------------------------------------------------------------------------------
/sample/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.2"
6 |
7 | defaultConfig {
8 | applicationId "com.wenming.androidprocess"
9 | minSdkVersion 14
10 | targetSdkVersion 20
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(dir: 'libs', include: ['*.jar'])
24 | testCompile 'junit:junit:4.12'
25 | compile 'com.android.support:appcompat-v7:23.1.1'
26 | compile 'com.android.support:design:23.1.1'
27 | compile project(':library')
28 | compile 'com.commit451:PhotoView:1.2.4'
29 | }
30 |
--------------------------------------------------------------------------------
/sample/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in D:\Android\AndroidSDK\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/sample/qrcode.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wenmingvs/AndroidProcess/0c05dd14279cc3dc32baffdbb94e76d5ead56f33/sample/qrcode.png
--------------------------------------------------------------------------------
/sample/src/androidTest/java/com/wenming/androidprocess/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package com.wenming.androidprocess;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase {
10 | public ApplicationTest() {
11 | super(Application.class);
12 | }
13 | }
--------------------------------------------------------------------------------
/sample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
13 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/wenming/androidprocess/Features.java:
--------------------------------------------------------------------------------
1 | package com.wenming.androidprocess;
2 |
3 | /**
4 | * Created by wenmingvs on 2016/1/14.
5 | */
6 | public class Features {
7 | public static int BGK_METHOD = 0;
8 | public static boolean showForeground = false;
9 | public static boolean showProfile = true;
10 | }
11 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/wenming/androidprocess/activity/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.wenming.androidprocess.activity;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.os.Bundle;
6 | import android.support.design.widget.TabLayout;
7 | import android.support.v4.view.ViewPager;
8 | import android.support.v7.app.AppCompatActivity;
9 | import android.support.v7.widget.Toolbar;
10 | import android.view.View;
11 |
12 | import com.wenming.andriodprocess.R;
13 | import com.wenming.androidprocess.Features;
14 | import com.wenming.androidprocess.adapter.ViewPagerAdapter;
15 | import com.wenming.androidprocess.fragment.OneFragment;
16 | import com.wenming.androidprocess.fragment.ProfileFragment;
17 | import com.wenming.androidprocess.service.MyService;
18 | import com.wenming.library.BackgroundUtil;
19 |
20 |
21 | public class MainActivity extends AppCompatActivity {
22 |
23 | private Toolbar toolbar;
24 | private TabLayout tabLayout;
25 | private ViewPager viewPager;
26 | private Context mContext;
27 | private Intent intent;
28 |
29 |
30 | @Override
31 | protected void onCreate(Bundle savedInstanceState) {
32 | super.onCreate(savedInstanceState);
33 | setContentView(R.layout.activity_main);
34 | mContext = this;
35 | initToolBar();
36 | initTabViewPager();
37 | Features.showForeground = true;
38 | intent = new Intent(mContext, MyService.class);
39 | startService(intent);
40 | }
41 |
42 | private void initToolBar() {
43 | toolbar = (Toolbar) findViewById(R.id.toolbar);
44 | setSupportActionBar(toolbar);
45 | getSupportActionBar().setDisplayHomeAsUpEnabled(true);
46 | toolbar.setVisibility(View.GONE);
47 | }
48 |
49 | private void initTabViewPager() {
50 | viewPager = (ViewPager) findViewById(R.id.viewpager);
51 | ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
52 | adapter.addFragment(new OneFragment(mContext), getString(R.string.tab1));
53 | adapter.addFragment(new ProfileFragment(mContext), getString(R.string.tab3));
54 | viewPager.setAdapter(adapter);
55 | tabLayout = (TabLayout) findViewById(R.id.tabs);
56 | tabLayout.setupWithViewPager(viewPager);
57 | viewPager.setCurrentItem(0, false);
58 | }
59 |
60 | @Override
61 | protected void onDestroy() {
62 | Features.showForeground = false;
63 | Features.BGK_METHOD = BackgroundUtil.BKGMETHOD_GETRUNNING_TASK;
64 | stopService(intent);
65 | super.onDestroy();
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/wenming/androidprocess/adapter/ViewPagerAdapter.java:
--------------------------------------------------------------------------------
1 | package com.wenming.androidprocess.adapter;
2 |
3 | import android.support.v4.app.Fragment;
4 | import android.support.v4.app.FragmentManager;
5 | import android.support.v4.app.FragmentPagerAdapter;
6 |
7 | import java.util.ArrayList;
8 | import java.util.List;
9 |
10 | /**
11 | * Created by wenmingvs on 2016/1/14.
12 | */
13 | public class ViewPagerAdapter extends FragmentPagerAdapter {
14 | private final List mFragmentList = new ArrayList<>();
15 | private final List mFragmentTitleList = new ArrayList<>();
16 |
17 | public ViewPagerAdapter(FragmentManager manager) {
18 | super(manager);
19 | }
20 |
21 | @Override
22 | public Fragment getItem(int position) {
23 | return mFragmentList.get(position);
24 | }
25 |
26 | @Override
27 | public int getCount() {
28 | return mFragmentList.size();
29 | }
30 |
31 | public void addFragment(Fragment fragment, String title) {
32 | mFragmentList.add(fragment);
33 | mFragmentTitleList.add(title);
34 | }
35 |
36 | @Override
37 | public CharSequence getPageTitle(int position) {
38 | return mFragmentTitleList.get(position);
39 | }
40 | }
--------------------------------------------------------------------------------
/sample/src/main/java/com/wenming/androidprocess/fragment/OneFragment.java:
--------------------------------------------------------------------------------
1 | package com.wenming.androidprocess.fragment;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.os.Build;
6 | import android.os.Bundle;
7 | import android.support.annotation.Nullable;
8 | import android.support.v4.app.Fragment;
9 | import android.view.LayoutInflater;
10 | import android.view.View;
11 | import android.view.ViewGroup;
12 | import android.widget.CheckBox;
13 | import android.widget.CompoundButton;
14 | import android.widget.RelativeLayout;
15 | import android.widget.Toast;
16 |
17 | import com.wenming.andriodprocess.R;
18 | import com.wenming.androidprocess.Features;
19 | import com.wenming.androidprocess.service.MyService;
20 | import com.wenming.library.BackgroundUtil;
21 |
22 | import java.util.ArrayList;
23 |
24 |
25 | /**
26 | * Created by wenmingvs on 2016/1/14.
27 | */
28 | public class OneFragment extends Fragment {
29 |
30 | private Context mContext;
31 | private View mView;
32 |
33 | private CheckBox checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6;
34 | private ArrayList reminderlist;
35 |
36 | @Override
37 | public void onCreate(Bundle savedInstanceState) {
38 | super.onCreate(savedInstanceState);
39 | reminderlist = new ArrayList();
40 | reminderlist.add(getResources().getString(R.string.reminder1));
41 | reminderlist.add(getResources().getString(R.string.reminder2));
42 | reminderlist.add(getResources().getString(R.string.reminder3));
43 | reminderlist.add(getResources().getString(R.string.reminder4));
44 | reminderlist.add(getResources().getString(R.string.reminder5));
45 | reminderlist.add(getResources().getString(R.string.reminder6));
46 | }
47 |
48 | public View onCreateView(LayoutInflater inflater, ViewGroup container,
49 | Bundle savedInstanceState) {
50 | mView = inflater.inflate(R.layout.fragment_one, container, false);
51 | initCheckBox();
52 | layoutClick();
53 | return mView;
54 | }
55 |
56 | @Override
57 | public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
58 | super.onViewStateRestored(savedInstanceState);
59 | }
60 |
61 | public OneFragment(Context context) {
62 | mContext = context;
63 | }
64 |
65 |
66 | private void startService() {
67 | Features.showForeground = true;
68 | Intent intent = new Intent(mContext, MyService.class);
69 | mContext.startService(intent);
70 | }
71 |
72 | private void initCheckBox() {
73 | checkBox1 = (CheckBox) mView.findViewById(R.id.checkbox1);
74 | checkBox2 = (CheckBox) mView.findViewById(R.id.checkbox2);
75 | checkBox3 = (CheckBox) mView.findViewById(R.id.checkbox3);
76 | checkBox4 = (CheckBox) mView.findViewById(R.id.checkbox4);
77 | checkBox5 = (CheckBox) mView.findViewById(R.id.checkbox5);
78 | checkBox6 = (CheckBox) mView.findViewById(R.id.checkbox6);
79 | checkBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
80 | @Override
81 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
82 | if (isChecked == true) {
83 | startService();
84 | deselectAll();
85 | checkBox1.setChecked(true);
86 | Features.BGK_METHOD = BackgroundUtil.BKGMETHOD_GETRUNNING_TASK;
87 | }
88 | }
89 | });
90 | checkBox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
91 | @Override
92 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
93 | if (isChecked == true) {
94 | startService();
95 | deselectAll();
96 | checkBox2.setChecked(true);
97 | Features.BGK_METHOD = BackgroundUtil.BKGMETHOD_GETRUNNING_PROCESS;
98 |
99 | }
100 | }
101 | });
102 | checkBox3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
103 | @Override
104 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
105 | if (isChecked == true) {
106 | startService();
107 | deselectAll();
108 | checkBox3.setChecked(true);
109 | Features.BGK_METHOD = BackgroundUtil.BKGMETHOD_GETAPPLICATION_VALUE;
110 |
111 | }
112 | }
113 | });
114 | checkBox4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
115 | @Override
116 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
117 | if (isChecked == true) {
118 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
119 | startService();
120 | deselectAll();
121 | checkBox4.setChecked(true);
122 | Features.BGK_METHOD = BackgroundUtil.BKGMETHOD_GETUSAGESTATS;
123 |
124 | } else {
125 | Toast.makeText(mContext, "此方法需要在Android5.0以上才能使用!", Toast.LENGTH_SHORT).show();
126 | checkBox4.setChecked(false);
127 | }
128 | }
129 | }
130 | });
131 |
132 | checkBox5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
133 | @Override
134 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
135 | if (isChecked == true) {
136 | startService();
137 | deselectAll();
138 | checkBox5.setChecked(true);
139 | Features.BGK_METHOD = BackgroundUtil.BKGMETHOD_GETACCESSIBILITYSERVICE;
140 | }
141 | }
142 | });
143 | checkBox6.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
144 | @Override
145 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
146 | if (isChecked == true) {
147 | startService();
148 | deselectAll();
149 | checkBox6.setChecked(true);
150 | Features.BGK_METHOD = BackgroundUtil.BKGMETHOD_GETLINUXPROCESS;
151 | }
152 | }
153 | });
154 |
155 |
156 | }
157 |
158 | public void layoutClick() {
159 | RelativeLayout relativeLayout = (RelativeLayout) mView.findViewById(R.id.clearForeground);
160 | relativeLayout.setOnClickListener(new View.OnClickListener() {
161 | @Override
162 | public void onClick(View v) {
163 | Features.showForeground = false;
164 | Intent intent = new Intent(mContext, MyService.class);
165 | mContext.stopService(intent);
166 | deselectAll();
167 | }
168 | });
169 | }
170 |
171 | private void deselectAll() {
172 | checkBox1.setChecked(false);
173 | checkBox2.setChecked(false);
174 | checkBox3.setChecked(false);
175 | checkBox4.setChecked(false);
176 | checkBox5.setChecked(false);
177 | checkBox6.setChecked(false);
178 | }
179 |
180 | }
181 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/wenming/androidprocess/fragment/ProfileFragment.java:
--------------------------------------------------------------------------------
1 | package com.wenming.androidprocess.fragment;
2 |
3 | import android.content.Context;
4 | import android.os.Bundle;
5 | import android.support.v4.app.Fragment;
6 | import android.view.KeyEvent;
7 | import android.view.LayoutInflater;
8 | import android.view.View;
9 | import android.view.ViewGroup;
10 | import android.webkit.WebView;
11 | import android.webkit.WebViewClient;
12 |
13 | import com.wenming.andriodprocess.R;
14 | import com.wenming.androidprocess.Features;
15 |
16 |
17 | /**
18 | * Created by wenmingvs on 2016/1/14.
19 | */
20 | public class ProfileFragment extends Fragment {
21 | private Context mContext;
22 | private View mView;
23 | private WebView mContentWv;
24 |
25 | public ProfileFragment(Context context) {
26 | mContext = context;
27 | }
28 |
29 | @Override
30 | public void onCreate(Bundle savedInstanceState) {
31 | super.onCreate(savedInstanceState);
32 | }
33 |
34 | public View onCreateView(LayoutInflater inflater, ViewGroup container,
35 | Bundle savedInstanceState) {
36 | mView = inflater.inflate(R.layout.profile_layout, container, false);
37 | mContentWv = (WebView) mView.findViewById(R.id.wv_webview_content);
38 | initWebView();
39 |
40 | return mView;
41 | }
42 |
43 | private void initWebView() {
44 | if (Features.showProfile) {
45 | mContentWv.getSettings().setJavaScriptEnabled(true);
46 | mContentWv.loadUrl("https://github.com/wenmingvs");
47 | mContentWv.setWebViewClient(new WebViewClient() {
48 | @Override
49 | public boolean shouldOverrideUrlLoading(WebView view, String url) {
50 | view.loadUrl(url);
51 | return true;
52 | }
53 | });
54 |
55 | mContentWv.setOnKeyListener(new View.OnKeyListener() {
56 | @Override
57 | public boolean onKey(View v, int keyCode, KeyEvent event) {
58 | if (event.getAction() == KeyEvent.ACTION_DOWN) {
59 | if (keyCode == KeyEvent.KEYCODE_BACK && mContentWv.canGoBack()) { //表示按返回键
60 | mContentWv.goBack(); //后退
61 | //webview.goForward();//前进
62 | return true; //已处理
63 | }
64 | }
65 | return false;
66 | }
67 | });
68 |
69 | }
70 | }
71 |
72 |
73 | }
74 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/wenming/androidprocess/receiver/MyReceiver.java:
--------------------------------------------------------------------------------
1 | package com.wenming.androidprocess.receiver;
2 |
3 | import android.content.BroadcastReceiver;
4 | import android.content.Context;
5 | import android.content.Intent;
6 |
7 | import com.wenming.androidprocess.Features;
8 | import com.wenming.androidprocess.service.MyService;
9 |
10 |
11 | /**
12 | * Created by wenmingvs on 2016/1/13.
13 | */
14 | public class MyReceiver extends BroadcastReceiver {
15 | @Override
16 | public void onReceive(Context context, Intent intent) {
17 | if (Features.showForeground) {
18 | Intent i = new Intent(context, MyService.class);
19 | context.startService(i);
20 | }
21 |
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/sample/src/main/java/com/wenming/androidprocess/service/MyService.java:
--------------------------------------------------------------------------------
1 | package com.wenming.androidprocess.service;
2 |
3 | import android.app.AlarmManager;
4 | import android.app.Notification;
5 | import android.app.NotificationManager;
6 | import android.app.PendingIntent;
7 | import android.app.Service;
8 | import android.content.Context;
9 | import android.content.Intent;
10 | import android.os.IBinder;
11 | import android.os.SystemClock;
12 | import android.support.v4.app.NotificationCompat;
13 | import android.util.Log;
14 |
15 | import com.wenming.andriodprocess.R;
16 | import com.wenming.androidprocess.Features;
17 | import com.wenming.androidprocess.activity.MainActivity;
18 | import com.wenming.androidprocess.receiver.MyReceiver;
19 | import com.wenming.library.BackgroundUtil;
20 |
21 | import java.util.ArrayList;
22 |
23 | /**
24 | * Created by wenmingvs on 2016/1/13.
25 | */
26 | public class MyService extends Service {
27 |
28 | private static final float UPDATA_INTERVAL = 0.5f;//in seconds
29 | private String status;
30 | private Context mContext;
31 | private ArrayList mContentList;
32 | private Notification notification;
33 | private AlarmManager manager;
34 | private PendingIntent pendingIntent;
35 | private NotificationCompat.Builder mBuilder;
36 | private Intent mIntent;
37 | private NotificationManager mNotificationManager;
38 | private static final int NOTICATION_ID = 0x1;
39 |
40 | @Override
41 | public IBinder onBind(Intent intent) {
42 | return null;
43 | }
44 |
45 | @Override
46 | public void onCreate() {
47 | super.onCreate();
48 | mContext = this;
49 | mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
50 | initContentData();
51 | startNotification();
52 | }
53 |
54 |
55 | @Override
56 | public int onStartCommand(Intent intent, int flags, int startId) {
57 | if (Features.showForeground) {
58 | manager = (AlarmManager) getSystemService(ALARM_SERVICE);
59 | int updateTime = (int) UPDATA_INTERVAL * 1000;
60 | long triggerAtTime = SystemClock.elapsedRealtime() + updateTime;
61 | Intent i = new Intent(mContext, MyReceiver.class);
62 | PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, i, 0);
63 | manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
64 | updateNotification();
65 |
66 | } else {
67 | stopForeground(true);
68 | mNotificationManager.cancelAll();
69 | stopSelf();
70 | }
71 | return Service.START_NOT_STICKY;
72 | }
73 |
74 | @Override
75 | public void onDestroy() {
76 | Features.showForeground = false;
77 | stopForeground(true);
78 | super.onDestroy();
79 | }
80 |
81 | private void startNotification() {
82 | status = getAppStatus() ? "前台" : "后台";
83 | mIntent = new Intent(mContext, MainActivity.class);
84 | pendingIntent = PendingIntent.getActivity(mContext, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);
85 | mBuilder = new NotificationCompat.Builder(mContext)
86 | .setSmallIcon(R.drawable.largeicon)
87 | .setContentText(mContentList.get(Features.BGK_METHOD))
88 | .setContentTitle("App处于" + status)
89 | .setAutoCancel(true)
90 | .setContentIntent(pendingIntent);
91 | notification = mBuilder.build();
92 | startForeground(NOTICATION_ID, notification);
93 | }
94 |
95 | private void updateNotification() {
96 | status = getAppStatus() ? "前台" : "后台";
97 | mBuilder.setContentTitle("App处于" + status);
98 | mBuilder.setContentText(mContentList.get(Features.BGK_METHOD));
99 | if (Features.BGK_METHOD == BackgroundUtil.BKGMETHOD_GETACCESSIBILITYSERVICE) {
100 | mBuilder.setContentTitle("请到LogCat中观察前后台变化");
101 | Log.d("wenming", "**方法五** App处于" + status);
102 | }
103 | notification = mBuilder.build();
104 | mNotificationManager.notify(NOTICATION_ID, notification);
105 | }
106 |
107 | private void initContentData() {
108 | mContentList = new ArrayList();
109 | mContentList.add("通过getRunningTask判断");
110 | mContentList.add("通过getRunningAppProcess判断");
111 | mContentList.add("通过ActivityLifecycleCallbacks判断");
112 | mContentList.add("通过UsageStatsManager判断");
113 | mContentList.add("通过AccessibilityService判断");
114 | mContentList.add("通过LinuxCoreInfo判断");
115 | }
116 |
117 | private boolean getAppStatus() {
118 | return BackgroundUtil.isForeground(mContext, Features.BGK_METHOD, mContext.getPackageName());
119 | }
120 |
121 |
122 | }
123 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable-xhdpi/clickbackground.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/sample/src/main/res/drawable-xhdpi/effectivematrixlogo.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wenmingvs/AndroidProcess/0c05dd14279cc3dc32baffdbb94e76d5ead56f33/sample/src/main/res/drawable-xhdpi/effectivematrixlogo.jpeg
--------------------------------------------------------------------------------
/sample/src/main/res/drawable-xhdpi/image1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wenmingvs/AndroidProcess/0c05dd14279cc3dc32baffdbb94e76d5ead56f33/sample/src/main/res/drawable-xhdpi/image1.png
--------------------------------------------------------------------------------
/sample/src/main/res/drawable-xhdpi/image2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wenmingvs/AndroidProcess/0c05dd14279cc3dc32baffdbb94e76d5ead56f33/sample/src/main/res/drawable-xhdpi/image2.png
--------------------------------------------------------------------------------
/sample/src/main/res/drawable-xhdpi/largeicon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wenmingvs/AndroidProcess/0c05dd14279cc3dc32baffdbb94e76d5ead56f33/sample/src/main/res/drawable-xhdpi/largeicon.png
--------------------------------------------------------------------------------
/sample/src/main/res/drawable-xhdpi/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wenmingvs/AndroidProcess/0c05dd14279cc3dc32baffdbb94e76d5ead56f33/sample/src/main/res/drawable-xhdpi/logo.png
--------------------------------------------------------------------------------
/sample/src/main/res/drawable-xhdpi/myicon.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wenmingvs/AndroidProcess/0c05dd14279cc3dc32baffdbb94e76d5ead56f33/sample/src/main/res/drawable-xhdpi/myicon.jpg
--------------------------------------------------------------------------------
/sample/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
13 |
14 |
21 |
22 |
28 |
29 |
30 |
35 |
36 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/fragment_one.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
17 |
18 |
26 |
27 |
32 |
33 |
41 |
42 |
51 |
52 |
60 |
61 |
69 |
70 |
78 |
79 |
80 |
87 |
88 |
97 |
98 |
106 |
107 |
115 |
116 |
123 |
124 |
125 |
126 |
133 |
134 |
143 |
144 |
152 |
153 |
161 |
162 |
169 |
170 |
171 |
178 |
179 |
188 |
189 |
197 |
198 |
206 |
207 |
214 |
215 |
216 |
223 |
224 |
233 |
234 |
242 |
243 |
251 |
252 |
259 |
260 |
261 |
262 |
269 |
270 |
279 |
280 |
288 |
289 |
297 |
298 |
305 |
306 |
307 |
308 |
309 |
317 |
318 |
319 |
327 |
328 |
329 |
330 |
331 |
332 |
333 |
--------------------------------------------------------------------------------
/sample/src/main/res/layout/profile_layout.xml:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/sample/src/main/res/menu/menu_main.xml:
--------------------------------------------------------------------------------
1 |
11 |
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wenmingvs/AndroidProcess/0c05dd14279cc3dc32baffdbb94e76d5ead56f33/sample/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wenmingvs/AndroidProcess/0c05dd14279cc3dc32baffdbb94e76d5ead56f33/sample/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wenmingvs/AndroidProcess/0c05dd14279cc3dc32baffdbb94e76d5ead56f33/sample/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wenmingvs/AndroidProcess/0c05dd14279cc3dc32baffdbb94e76d5ead56f33/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wenmingvs/AndroidProcess/0c05dd14279cc3dc32baffdbb94e76d5ead56f33/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/sample/src/main/res/values-v21/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/sample/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | #FFFFFF
5 | #FFFFFF
6 | #000000
7 |
8 |
9 | #EEEEEE
10 | #FFFFFF
11 |
12 |
13 | #125688
14 | #125688
15 | #c8e8ff
16 |
17 |
18 | #E14638
19 | #E14638
20 | #F7B7B2
21 |
22 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 | 264dp
6 | 16dp
7 | 14sp
8 | 72dp
9 |
10 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | ProcessDemo
3 | Settings
4 | Hello World from section: %1$d
5 |
6 | App是否后台方法
7 | 通知的样式
8 | 关于我
9 |
10 | 方法1:\ngetRunningTask方法在Android5.0以上已经被废弃,只会返回自己和系统的一些不敏感的task,不再返回其他应用的task,用此方法来判断自身App是否处于后台,仍然是有效的,但是无法判断其他应用是否位于前台,因为不再能获取信息
11 | 方法2:\ngetRunningAppProcesses方法在Nexus5上测试正常,但是在小米Note上测试失败,因为在聊天类型的App中,常常需要常驻后台来不间断的获取服务器的消息,如果把我们把Service设置成START_STICKY来保证Service重启来达到常驻后台的效果,就会被小米系统判断是前台,appProcess.importance的值永远都会是forground,所以无法区别前后台
12 | 方法3:\n通过ActivityLifecycleCallbacks来批量管理Activity的生命周期,进而实现判断,此方法在API 14以上均有效,\n\n\n注意:\n1. 请务必在Application中注册此回调接口
13 | 方法4:\n通过使用UsageStatsManager获取,此方法是Android5.0之后提供的新API,可以获取一个时间段内的应用统计信息\n\n\n注意:\n1. 务必提供在AndroidManifest中加入对应的权限\n2. 打开手机设置,点击安全-高级,在有权查看使用情况的应用中,为这个App打上勾
14 | 方法5:\nLinux系统内核会把Process进程信息保存在/proc目录下,通过遍历进程的属性信息来判断位于前台的任一应用
15 | 方法6:\n通过Android自带的无障碍功能,监控窗口焦点的变化,进而拿到当前焦点窗口对应的包名
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/sample/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
15 |
16 |
17 |
18 |
19 |
20 |
23 |
24 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/sample/src/test/java/com/wenming/androidprocess/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.wenming.androidprocess;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest {
11 | @Test
12 | public void addition_isCorrect() throws Exception {
13 | assertEquals(4, 2 + 2);
14 | }
15 | }
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':sample', ':library'
2 |
--------------------------------------------------------------------------------