Created
September 24, 2018 14:09
-
-
Save gbzarelli/f9cdf16113c2bb0f28f115baac529464 to your computer and use it in GitHub Desktop.
Arquivo BuildConfig útil para utilização em bibliotecas aonde não tem como pegar as informações do projeto devido ao import. BuildConfig file useful for use in libraries where you can not get project information due to import.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package br.com.grupocriar.swapandroid.utils | |
import android.content.Context | |
import java.lang.reflect.Field | |
object BuildConfigHelper { | |
val FIELD_DEBUG = "DEBUG" | |
val FIELD_APPLICATION_ID = "APPLICATION_ID" | |
val FIELD_BUILD_TYPE = "BUILD_TYPE" | |
val FIELD_FLAVOR = "FLAVOR" | |
val FIELD_VERSION_CODE = "VERSION_CODE" | |
val FIELD_VERSION_NAME = "VERSION_NAME" | |
fun getDebug(context: Context): Boolean { | |
val o = getBuildConfigValue(context, FIELD_DEBUG) | |
return if (o != null && o is Boolean) { | |
(o as Boolean?)!! | |
} else { | |
false | |
} | |
} | |
fun getVersionCode(context: Context): Int { | |
val o = getBuildConfigValue(context, FIELD_VERSION_CODE) | |
return if (o != null && o is Int) { | |
(o as Int?)!! | |
} else { | |
Integer.MIN_VALUE | |
} | |
} | |
/** | |
* Gets a field from the project's BuildConfig. This is useful when, for example, flavors | |
* are used at the project level to set custom fields. | |
* | |
* @param context Used to find the correct file | |
* @param fieldName The name of the field-to-access | |
* @return The value of the field, or `null` if the field is not found. | |
*/ | |
fun getBuildConfigValue(context: Context, fieldName: String): Any? { | |
try { | |
val clazz = Class.forName(context.packageName + ".BuildConfig") | |
val field = clazz.getField(fieldName) | |
return field.get(null) | |
} catch (e: ClassNotFoundException) { | |
e.printStackTrace() | |
} catch (e: NoSuchFieldException) { | |
e.printStackTrace() | |
} catch (e: IllegalAccessException) { | |
e.printStackTrace() | |
} | |
return null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment