android+os+stack,android.os.Debug

发现代码之美

日志

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 "";

}

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;

拓展

通过此方法是不是能达到打断点看业务代码流程的效果?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值