发现代码之美
日志
05-08 17:01:07.156 997 997 W ContextImpl: Calling a method in the system process without a qualified user: android.app.ContextImpl.sendBroadcast:877 android.content.ContextWrapper.sendBroadcast:421 com.galanz.ovena6.ui.setting.FactoryResetConfirmActivity$cleanData$1$2.invokeSuspend:94 kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith:33 kotlinx.coroutines.DispatchedTask.run:241
追问
它是怎么实现这行日志的打印?
代码跟踪
1.android.app.ContextImpl.sendBroadcast
public void sendBroadcast(Intent intent) {
warnIfCallingFromSystemProcess();
····
}
2.android.app.ContextImpl.warnIfCallingFromSystemProcess
private void warnIfCallingFromSystemProcess() {
if (Process.myUid() == Process.SYSTEM_UID) {
Slog.w(TAG, "Calling a method in the system process without a qualified user: "
+ Debug.getCallers(5));
}
}
3.android.os.Debug.getCallers
/**
* Return a string consisting of methods and locations at multiple call stack levels.
* @param depth the number of levels to return, starting with the immediate caller.
* @return a string describing the call stack.
* {@hide} //注意这个方法是hide
*/
public static String getCallers(final int depth) {
final StackTraceElement[] callStack = Thread.currentThread().getStackTrace();//高级货
StringBuffer sb = new StringBuffer();
for (int i = 0; i < depth; i++) {
sb.append(getCaller(callStack, i)).append(" ");
}
return sb.toString();
}
private static String getCaller(StackTraceElement callStack[], int depth) {
// callStack[4] is the caller of the method that called getCallers()
if (4 + depth >= callStack.length) {
return "<bottom of call stack>";
}
StackTraceElement caller = callStack[4 + depth];//从StackTraceElement中获取各种变量
return caller.getClassName() + "." + caller.getMethodName() + ":" + caller.getLineNumber();//输出特定的日志格式
}
关键分析
1.通过当前线程(Thread.currentThread())中获取栈信息
StackTraceElement[] callStack = Thread.currentThread().getStackTrace();
2.每个StackTraceElement对象包含各种变量:
class StackTraceElement implements java.io.Serializable
private String declaringClass;
private String methodName;
private String fileName;
private int lineNumber;
拓展
通过此方法是不是能达到打断点看业务代码流程的效果?
网友评论