本文主要讲述python 脚本获取android 应用使用情况。
主要思路:使用adb 获取当前activity ,1s 一次输出。
主要涉及知识点:
具体代码实现如下:
#!/usr/bin/python
#coding=utf-8
import matplotlib.pyplot as plt
import os
import time
adb_cmd = "adb shell 'dumpsys activity | grep \"Recent #0\"' > usage_log.txt"
while True:
result = os.popen(adb_cmd).read()
currentTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
with open('usage_log.txt', 'r') as f:
lines = f.readlines();
for line in lines:
with open('usage.txt', 'a') as f:
f.write(currentTime)
f.write(line)
plt.pause(1)
具体的输出会生成两个文件:
usage_log.txt:
* Recent #0: Task{c73bebe #2 visible=false type=home mode=fullscreen translucent=true I=com.oppo.launcher/.Launcher U=0 StackId=1 sz=1}
usage.txt:
2023-11-20 13:39:39 * Recent #0: Task{c73bebe #2 visible=false type=home mode=fullscreen translucent=true I=com.oppo.launcher/.Launcher U=0 StackId=1 sz=1}
2023-11-20 13:39:40 * Recent #0: Task{c73bebe #2 visible=false type=home mode=fullscreen translucent=true I=com.oppo.launcher/.Launcher U=0 StackId=1 sz=1}
2023-11-20 13:39:41 * Recent #0: Task{a730670 #648 visible=true type=standard mode=fullscreen translucent=false A=10328:com.tencent.mm U=0 StackId=648 sz=3}
2023-11-20 13:39:42 * Recent #0: Task{c73bebe #2 visible=false type=home mode=fullscreen translucent=true I=com.oppo.launcher/.Launcher U=0 StackId=1 sz=1}
2023-11-20 13:39:44 * Recent #0: Task{d6183e9 #646 visible=true type=standard mode=fullscreen translucent=false A=10327:com.ss.android.ugc.aweme U=0 StackId=646 sz=1}
2023-11-20 13:39:45 * Recent #0: Task{d6183e9 #646 visible=true type=standard mode=fullscreen translucent=false A=10327:com.ss.android.ugc.aweme U=0 StackId=646 sz=1}
2023-11-20 13:39:46 * Recent #0: Task{c73bebe #2 visible=false type=home mode=fullscreen translucent=true I=com.oppo.launcher/.Launcher U=0 StackId=1 sz=1}
2023-11-20 13:39:47 * Recent #0: Task{1f4ffa2 #649 visible=true type=standard mode=fullscreen translucent=false A=10288:com.zh.xpose U=0 StackId=649 sz=1}
2023-11-20 13:39:49 * Recent #0: Task{6853b11 #650 visible=true type=standard mode=fullscreen translucent=false A=10287:com.test.dexpoxed U=0 StackId=650 sz=1}
2023-11-20 13:39:50 * Recent #0: Task{c73bebe #2 visible=false type=home mode=fullscreen translucent=true I=com.oppo.launcher/.Launcher U=0 StackId=1 sz=1}
2023-11-20 13:39:51 * Recent #0: Task{a730670 #648 visible=true type=standard mode=fullscreen translucent=false A=10328:com.tencent.mm U=0 StackId=648 sz=3}
2023-11-20 13:39:52 * Recent #0: Task{c73bebe #2 visible=false type=home mode=fullscreen translucent=true I=com.oppo.launcher/.Launcher U=0 StackId=1 sz=1}