Code Monkey home page Code Monkey logo

gradle-android-buildconstants-plugin's Introduction

Android Build Constants Plugin Build Status

A Gradle plugin for Android which generates both Java and XML constants as part of the build process.

Why do I need this?

In short: To define constants that are accessible from everywhere in your Android app.

In long: There are two ways to define constants in Android. Both have their limitations.

  • Creating constants using buildConfigField only adds entries to BuildConfig.java which means you cannot access them via XML.
  • Creating a custom constants.xml resource file with entries like <string name="constant">constant_value</string> lets you easily reference the constant via @string/constant in XML, but requires you to have a Context object on the Java side to get the value using getResources().getString(R.string.constant).

None of the above solutions is ideal. This plugin lets you specify constants in your build.gradle file that will be translated into both a Java and an XML-based version with the same constant value.

How does it work?

The plugin creates a new task per build type, e.g. generateDebugBuildConstants. It hooks into the build process ahead of the processDebugResources task so it will be executed every time you assemble your project. It supports incremental builds, i.e. if none of the inputs or outputs have changed, Gradle can skip the task (up-to-date).

Usage

The plugin currently supports Integer, Boolean and String data types.

You can specify the constants using a closure in your build.gradle file like this:

buildConstants {
  constants {
    aBoolean = true
    aString = 'string'
    aNumber = 123
  }
}

The plugin will then generate both a Java and an XML version of the constants like so:

Java:

public final class BuildConstants {
  
  public static final boolean ABOOLEAN = true;
  public static final String ASTRING = "string";
  public static final int ANUMBER = 123;
  
  private BuildConstants() {
    throw new AssertionError("No instances.");
  }
}

XML:

<resources>
	<bool name="aboolean">true</bool>
	<string name="astring">string</string>
	<integer name="anumber">123</integer>
</resources>

Alternatively, you can define the constants using a map:

buildConstants {
  constants = [
    aBoolean : true,
    aString : 'string',
    aNumber : 123
  ]
}

Or specify just a single constant (similar to buildConfigField):

buildConstants {
  constant 'single_constant', 'single_string'
}

The default generated file names are BuildConstants.java and build_constants.xml. You can change them like this:

buildConstants {
  javaFileName 'SampleBuildConstants'
  xmlFileName 'sample_build_constants'
}

Example

Check out the sample project for an example implementation.

Download

Build script snippet for use in all Gradle versions:

buildscript {
  repositories {
    maven {
      url 'https://plugins.gradle.org/m2/'
    }
  }
  dependencies {
    classpath 'gradle.plugin.com.jenzz:buildconstants:1.1.0'
  }
}

apply plugin: 'com.jenzz.buildconstants'

Build script snippet for new, incubating, plugin mechanism introduced in Gradle 2.1:

plugins {
  id 'com.jenzz.buildconstants' version '1.1.0'
}

License

This project is licensed under the MIT License.

gradle-android-buildconstants-plugin's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

Forkers

drive24f

gradle-android-buildconstants-plugin's Issues

Missing support for productFlavors

After I added the :

apply plugin: "com.jenzz.buildconstants"

I've this error.
More details:

Caused by: java.lang.NullPointerException: Cannot invoke method dependsOn() on null object
    at com.jenzz.buildconstants.BuildConstantsPlugin$_apply_closure1$_closure2.doCall(BuildConstantsPlugin.groovy:34)
    at com.jenzz.buildconstants.BuildConstantsPlugin$_apply_closure1.doCall(BuildConstantsPlugin.groovy:20)
    at org.gradle.listener.ClosureBackedMethodInvocationDispatch.dispatch(ClosureBackedMethodInvocationDispatch.java:40)
    at org.gradle.listener.ClosureBackedMethodInvocationDispatch.dispatch(ClosureBackedMethodInvocationDispatch.java:25)
    at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:44)
    at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:79)
    at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:30)
    at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy10.afterEvaluate(Unknown Source)
    at org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:67)
    ... 65 more

How can I solve?

Unsupported major.minor version 52.0

Hi @jenzz ,

I've added your plugin to my project, but i'm having the following error:

Error:(33, 0) Cause: com/jenzz/buildconstants/BuildConstantsPlugin : Unsupported major.minor version 52.0

You can check the commit where I've added this plugin to the project: Commit (Citikey/citikey-android - feature/constants)

And here you have my ./gradlew version info:

$ ./gradlew -v

------------------------------------------------------------
Gradle 2.10
------------------------------------------------------------

Build time:   2015-12-21 21:15:04 UTC
Build number: none
Revision:     276bdcded730f53aa8c11b479986aafa58e124a6

Groovy:       2.4.4
Ant:          Apache Ant(TM) version 1.9.3 compiled on December 23 2013
JVM:          1.8.0_77 (Oracle Corporation 25.77-b03)
OS:           Windows 10 10.0 amd64

Regards,
Llorens

PS: I've always been creating my two constant files manually. If this plugin work, it would be a great time saver. ๐Ÿ˜

Allow different configurations per product flavor

Ideally following the style of the android closure allowing to override less specific configs, for example:

android {

  ...

    defaultConfig {
        applicationId 'com.jenzz.buildconstants.sample'
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName '1.0.0'
  }

  flavorDimensions 'abi', 'version'

  productFlavors {
    free {
      dimension 'version'
    }
    pro {
      dimension 'version'
    }
    arm {
      dimension "abi"
    }
    mips {
      dimension "abi"
    }
    x86 {
      dimension "abi"
    }
  }
}

buildConstants {

    defaultConfig {
        fileNames {
            java 'SampleBuildConstants'
            xml 'sample_build_constants'
        }
        constants {
            aString = 'string'
        }
    }

    // overrides defaultConfig
    freeDebug {
        fileNames {
            java 'SampleBuildConstants2'
            xml 'sample_build_constants_2'
        }
        constants {
            aString = 'string_two'
        }
    }

    // overrides freeDebug
    armFreeDebug {
        fileNames {
            java 'BuildConstantsFlavor3'
            xml 'build_constants_flavor3'
        }
        constants {
            aString = 'string_three'
        }
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.