APP启动的两种方式
冷启动:第一次启动APP
热启动:APP通过“back”键或“home”键在后台运行(未被杀死 ),再次启动恢复运行
ADB命令获得APP启动时间
冷启动—启动APP命令:
使用的是adb shell am 命令,start代表启动APP, -W参数代表等待启动完成,-n后面接APP包名和activity名。(关于APP包名和activity名查询可参考这里)
adb shell am start -W -n 包名/activity名
运行命令结果如下图:当中ThisTime就是APP启动时间
冷启动—关闭APP命令:
使用的是adb shell am 命令,force-stop代表关闭指定包命的APP。
adb shell am force-stop 包名
热启动—启动APP命令:
和冷启动一样
adb shell am start -W -n 包名/activity名
热启动—关闭APP命令:
通过输入按键事件“3”模拟“back”按键,将程序变为后台执行状态。
adb shell input keyevent 3
启动时间测试脚本实现
我们在人工进行启动测试的过程就是:通过启动命令启动APP,然后记录启动时间,通过命令关闭APP;一次一次重复着,接下来我们就用python3代码实现这一过程。
#encoding=utf-8
import os
import time
import csv
class App(object):
def __init__(self):
self.result=''
self.launchedTime=-1
#加载app
def launchApp(self):
cmd='adb shell am start -W -n com.android.gallery3d/.app.GalleryActivity'
self.result=os.popen(cmd)
#关闭app
def stopApp(self,flag=True):
if flag==True:
#冷启动
cmd='adb shell am force-stop com.android.gallery3d'
else:
#热启动
cmd='adb shell input keyevent 3'
os.popen(cmd)
#获得加载时间
def getLanchedTime(self):
for line in self.result.readlines():
if 'ThisTime' in line:
self.launchedTime=line.split(':')[1]
break
return self.launchedTime
class Controller():
def __init__(self):
self.app=App()
self.allData=[('startTime','launchedTime')]
#运行
def run(self,count,flag=True):
while(count>0):
nowtime=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
self.app.launchApp()
launedTime=self.app.getLanchedTime()
time.sleep(2)
self.allData.append((nowtime,launedTime))
self.app.stopApp(flag)
time.sleep(2)
count=count-1
#将数据保存到CSV文件中
def saveDataToCSV(self,path):
file=open(path,'w')
writer=csv.writer(file)
writer.writerows(self.allData)
file.close()
if __name__=='__main__':
controller=Controller()
controller.run(10,flag=True)
controller.saveDataToCSV('launchedTime.csv')
得到的耗时数据csv文件如下图:我们可以选择用Excel打开进行分析。
要说明的是我们将APP运行的时间和启动耗时,一对一对的存在csv文件中,学习到这里我当时想为什么是csv文件,而不是excel文件。于是乎,我查了一下两个文件的区别,大致的意思就是csv文件是纯文本文件,Excel文件还包含了许多格式信息,所以仅仅是为了保存数据,csv文件体积更小,创建读取更方便。
另一方面,我们在进行数据结果分析时(求平均值,画曲线图等),要去掉第一次数据,因为在测试热启动耗时过程中,第一次启动APP属于冷启动,影响实际结果。
最后,我们得到的启动耗时平均值如何来衡量呢?两个维度,一个是业界内同类产品的平均启动耗时,另一个是自身与之前版本比较是否有较大的差异。