Android如何区分debug和release两种状态

BuildConfig.DEBUG

Android开发中识别debug还是release状态还是很有用的,比如说打印日志,有些日志开发的时候需要,可是线上正式包不需要,这时知道debug状态就可以很方便的隐藏非必要日志而又不影响开发。

一般使用BuildConfig.DEBUG来获取应用的状态,debug包返回true, release返回false

但是在主Moudle里是好使的,在Library里面,无论是debug包还是release都是返回false

解决办法:BuildConfig是build过程中生成的文件,在Library的build.gradle中配置

gradle.startParameter.getTaskNames().each { task ->
    println("task: " + task)
    //library里 BuildConfig.DEBUG默认一直是flase,所以需要自定义
    if (task.contains("Debug")) {
        android {
            defaultPublishConfig "debug"
        }
    } else if (task.contains("Release")) {
        android {
            defaultPublishConfig "release"
        }
    }
}

配置后,BuildConfig.DEBUG即可返回正常值

ApplicationInfo.FLAG_DEBUGGABLE

那么还有没有其他方法识别debug和release两种状态呢?可以通过获取标志ApplicationInfo.FLAG_DEBUGGABLE

public boolean isDebug(Context context) {
    boolean isDebug = context.getApplicationInfo() != null &&
        (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
  return isDebug;
}

该方案有个注意事项就是:App Module 的清单文件中不能主动设置 android:debuggable,否则无论 Debug 还是 Release 版会始终是设置的值。当然本身就没有主动设置的必要。

上一篇 Android反编译
下一篇 Android ListView addScrapView ArrayIndexOutOfBoundsException
目录
文章列表
1 Swift - 下标脚本方法介绍及实例
Swift - 下标脚本方法介绍及实例
2
Java中String与BufferedReader、InputStream转换
Java中String与BufferedReader、InputStream转换
3
设计模式(7)策略模式
设计模式(7)策略模式
4
Spring Cloud Gray 配置参数
Spring Cloud Gray 配置参数
5
Python线程池实现
Python线程池实现
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。