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

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

一般,大家会用BuildConfig.DEBUG来获取应用的状态,debug包返回true, release返回false;但是在主Moudle里面是好使的,在Library里面,无论是debug包还是release都是返回false。那怎么办呢,要是控制日志的方法在Library里面不就不好用了吗?

解决这个问题那还是有办法的,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还是正常返值的。

那么还有没有其他的方法来识别debug和release两种状态呢?还是有的,不需要用到BuildConfig。

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 版会始终是设置的值。当然本身就没有自动设置的必要。

发布了24 篇原创文章 · 获赞 4 · 访问量 8778

猜你喜欢

转载自blog.csdn.net/wusejiege6/article/details/102753427
今日推荐