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