我是靠谱客的博主 精明糖豆,这篇文章主要介绍Android 技巧 —— Debug 判断不再用 BuildConfig,现在分享给大家,希望可以做个参考。

解决方案:使用 ApplicationInfo.FLAG_DEBUGGABLE

反编译 Debug 包和 Release 包对比看看有没有区别,会发现他们 AndroidManifest.xml 中 application 节点的 android:debuggable 值是不同的。

Debug 包值为 true,Release 包值为 false,这是编译自动修改的。

所以我们考虑通过 ApplicationInfo 的这个属性去判断是否是 Debug 版本,如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class AppUtils { private static Boolean isDebug = null; public static boolean isDebug() { return isDebug == null ? false : isDebug.booleanValue(); } /** * Sync lib debug with app's debug value. Should be called in module Application * * @param context */ public static void syncIsDebug(Context context) { if (isDebug == null) { isDebug = context.getApplicationInfo() != null && (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; } } }

在自己的 Application 内调用进行初始化,

复制代码
1
2
AppUtils.syncIsDebug(getApplicationContext());

这样以后调用 AppUtils.isDebug() 即可判断是否是 Debug 版本。同时适用于 Module 是 Lib 和 applicationId 被修改的情况,比 BuildConfig.DEBUG 靠谱的多。

这个方案有个注意事项就是自己 App Module 中不能主动设置 android:debuggable,否则无论 Debug 还是 Release 版会始终是设置的值。

当然本身就没有自动设置的必要。

最后

以上就是精明糖豆最近收集整理的关于Android 技巧 —— Debug 判断不再用 BuildConfig的全部内容,更多相关Android内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(91)

评论列表共有 0 条评论

立即
投稿
返回
顶部