感谢:
https://github.com/markzhai/AndroidPerformanceMonitor
http://blog.csdn.net/xiaodanpeng/article/details/53503076
涉及到UI性能问题我们需要直面的就是卡顿,为了让应用更加流畅我们不得不做一些监控,从而能及时修复卡顿现象还用户一个丝滑的体验。本文主要讲解利用UI线程Looper的方式来监控卡顿问题并结合AndroidPerformanceMonitor来深入理解。
原理篇
在Android中的UI线程有Looper它会执行loop方法不断的从消息队列中取出Message然后执行,看一眼源码:
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
msg.recycleUnchecked();
}
}
其实原理很简单就是给Looper中的Printer logging对象赋值,logging开始的时候会打印出">>>>> Dispatching to "开头的日志、结束的时候会打印出"<<<<< Finished to "结尾的日志。所以,我们可以新建一个Printer对象进行监听,如果两个日志之间的耗时超过我们规定的时间那么就抛出卡顿日志到控制台,可以简单模拟一个伪代码 类似:
public class BlockPrinter implements Printer {
private static final String BLOCK_START = ">>>>> Dispatching";
private static final String BLOCK_END = "<<<<< Finished";
@Override
public void println(String x) {
if (x.startsWith(BLOCK_START)) {
long startTime;
}
if (x.startsWith(BLOCK_END)) {
long endTime;
}
if (endTime - startTime > timeOut) {
// 如果两条日志间隔时间超时了
// 抛出卡顿日志...
}
}
}
接下来只要Looper.getMainLooper().setMessageLogging(new BlockPrinter());
把这个Printer对象设置给UI线程的Looper就能愉快的监听卡顿了。
带着这个原理 接下来看下AndroidPerformanceMonitor
源码。
主要源码篇
先从源码仓库的sample中找到入口:BlockCanary.install(this, new AppContext()).start()
最后会走入BlockCanary
的构造函数中去:
private BlockCanary() {
BlockCanaryInternals.setContext(BlockCanaryContext.get());
mBlockCanaryCore = BlockCanaryInternals.getInstance();
mBlockCanaryCore.addBlockInterceptor(BlockCanaryContext.get());
if (!BlockCanaryContext.get().displayNotification()) {
return;
}
mBlockCanaryCore.addBlockInterceptor(new DisplayService());
}
所以主要的类是BlockCanaryInternals
在这个类中分别有三个主要的对象:
LooperMonitor monitor;
StackSampler stackSampler;
CpuSampler cpuSampler;
其中StackSampler、CpuSampler
都是 extends
AbstractSampler
所以需要先进入AbstractSampler
看个明白。
abstract class AbstractSampler {
private static final int DEFAULT_SAMPLE_INTERVAL = 300;
protected AtomicBoolean mShouldSample = new AtomicBoolean(false);
protected long mSampleInterval;
private Runnable mRunnable = new Runnable() {
@Override
public void run() {
doSample();
if (mShouldSample.get()) {
HandlerThreadFactory.getTimerThreadHandler()
.postDelayed(mRunnable, mSampleInterval);
}
}
};
public AbstractSampler(long sampleInterval) {
if (0 == sampleInterval) {
sampleInterval = DEFAULT_SAMPLE_INTERVAL;
}
mSampleInterval = sampleInterval;
}
/**
* 当>>>>> Dispatching日志来的时候 执行start方法
*/
public void start() {
if (mShouldSample.get()) {
return;
}
mShouldSample.set(true);
/**
* HandlerThreadFactory.getTimerThreadHandler 进入源码可以看出 其实就是
HandlerThread handlerThread = new HandlerThread("BlockCanary-" + threadName);
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
*/
// 先取消上一次 / 或者可能没有被取消的Callback
HandlerThreadFactory.getTimerThreadHandler().removeCallbacks(mRunnable);
// getSampleDelay = 两条日志的间隔时间 也就是说 如果超时了发生卡顿会执行mRunnable
HandlerThreadFactory.getTimerThreadHandler().postDelayed(mRunnable,
BlockCanaryInternals.getInstance().getSampleDelay());
}
/**
* 当 <<<<< Finished 日志来的时候 执行stop方法
*/
public void stop() {
if (!mShouldSample.get()) {
return;
}
mShouldSample.set(false);
HandlerThreadFactory.getTimerThreadHandler().removeCallbacks(mRunnable);
}
abstract void doSample();
}
通过查看注释明白主要采取的是Handler.postDelay的方式,如果结束日志打印出来的时候就执行removeCallbacks,而如果发生了卡顿也就是说还来不及removeCallbacks就会执行doSample方法了,而这个方法分别在StackSampler、CpuSampler
中实现了。
首先,如果发生了卡顿那么进入StackSampler.doSample
protected void doSample() {
StringBuilder stringBuilder = new StringBuilder();
for (StackTraceElement stackTraceElement : mCurrentThread.getStackTrace()) {
stringBuilder
.append(stackTraceElement.toString())
.append(BlockInfo.SEPARATOR);
}
synchronized (sStackMap) {
if (sStackMap.size() == mMaxEntryCount && mMaxEntryCount > 0) {
sStackMap.remove(sStackMap.keySet().iterator().next());
}
sStackMap.put(System.currentTimeMillis(), stringBuilder.toString());
}
}
这里主要是通过StackTraceElement
类把堆栈信息保存到Map中去。
其次,进入CpuSampler.doSample
这个方法比较有意思,会根据本地文件分析Cpu相关信息:
protected void doSample() {
BufferedReader cpuReader = null;
BufferedReader pidReader = null;
try {
cpuReader = new BufferedReader(new InputStreamReader(
new FileInputStream("/proc/stat")), BUFFER_SIZE);
String cpuRate = cpuReader.readLine();
if (cpuRate == null) {
cpuRate = "";
}
if (mPid == 0) {
mPid = android.os.Process.myPid();
}
pidReader = new BufferedReader(new InputStreamReader(
new FileInputStream("/proc/" + mPid + "/stat")), BUFFER_SIZE);
String pidCpuRate = pidReader.readLine();
if (pidCpuRate == null) {
pidCpuRate = "";
}
parse(cpuRate, pidCpuRate);
} catch (Throwable throwable) {
Log.e(TAG, "doSample: ", throwable);
} finally {
try {
if (cpuReader != null) {
cpuReader.close();
}
if (pidReader != null) {
pidReader.close();
}
} catch (IOException exception) {
Log.e(TAG, "doSample: ", exception);
}
}
}
这一块知识可以参考链接,就不多做解释了:http://blog.csdn.net/xiaodanpeng/article/details/53503076
最后,LooperMonitor
这个类就是原理分析中的Printer对象,最终是要给Looper赋值的。而Printer打印日志的时候都会执行println
这个方法
public void println(String x) {
if (mStopWhenDebugging && Debug.isDebuggerConnected()) {
return;
}
if (!mPrintingStarted) {
mStartTimestamp = System.currentTimeMillis();
mStartThreadTimestamp = SystemClock.currentThreadTimeMillis();
mPrintingStarted = true;
startDump();
} else {
final long endTime = System.currentTimeMillis();
mPrintingStarted = false;
if (isBlock(endTime)) {
notifyBlockEvent(endTime);
}
stopDump();
}
}
private void startDump() {
if (null != BlockCanaryInternals.getInstance().stackSampler) {
BlockCanaryInternals.getInstance().stackSampler.start();
}
if (null != BlockCanaryInternals.getInstance().cpuSampler) {
BlockCanaryInternals.getInstance().cpuSampler.start();
}
}
private void stopDump() {
if (null != BlockCanaryInternals.getInstance().stackSampler) {
BlockCanaryInternals.getInstance().stackSampler.stop();
}
if (null != BlockCanaryInternals.getInstance().cpuSampler) {
BlockCanaryInternals.getInstance().cpuSampler.stop();
}
}
这里主要就是执行了AbstractSampler: start 和 stop 方法
也就是上面的分析的原理:采用Handler.postDelay的方式,如果没有发生卡顿就removeCallbacks而相反的话就会抛出卡顿以及cpu相关的信息。
Ok、好像也差不多了于是开启监控,这样子当发生了卡顿就会抛出卡顿信息出来。
/**
* Start monitoring.
*/
public void start() {
if (!mMonitorStarted) {
mMonitorStarted = true;
Looper.getMainLooper().setMessageLogging(mBlockCanaryCore.monitor);
}
}
源码通过参考LeakCanary
有做了类似的界面,界面中上面的是CPU相关信息,下面的是卡顿的堆栈日志信息,不过跟UI性能感觉不上多大关系就不做分析。
综上,日常可以把这个开源项目集成到项目中去,通过卡顿日志能并及时的修复,这样就能确保一个流畅的app。