Android 技巧 —— Debug 判断不再用 BuildConfig

本文介绍了一种方法来判断Android应用是否为Debug版本,主要通过检查ApplicationInfo.FLAG_DEBUGGABLE属性。在Application中初始化,避免了直接依赖BuildConfig.DEBUG的不稳定性,适用于Library Module和applicationId修改的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解决方案:使用 ApplicationInfo.FLAG_DEBUGGABLE

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

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

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


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 内调用进行初始化,

AppUtils.syncIsDebug(getApplicationContext());

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

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

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值