For example, read version from JSON file. In build.gradle, in my case it is in: /app/build.gradle write something like:

def computeVersionName() {
    def f1 = new File("app/src/main/assets/version.json");
    def json = new JsonSlurper().parseText(f1.text)

    assert json instanceof Map
    return json.version
}

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"
    defaultConfig {
        applicationId 'myId'
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 2
        versionName computeVersionName()
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

Notice:

versionName computeVersionName()