在Android Studio中为Android应用程序设置开发和生产环境

时间:2018-03-08 07:26:03

标签: android android-studio kotlin android-gradle

关于这个问题我有两个问题。

  1. 如果在laravel / web中我们有.env个文件来将环境设置为" development"或生产并自动连接到不同的数据库。在android / kotlin / android studio中怎么样?

  2. 以及如何将我的应用程序请求发送到PC上的本地主机(127.0.2.1),如果它在"开发"环境和对真实网址API的请求,如果它在"生产"环境。仅供参考,我不使用模拟器。我用手机测试我的应用程序。

1 个答案:

答案 0 :(得分:0)

是的,这也适用于您的Android应用程序。您只需修改build.gradle文件即可根据开发,测试或生产环境管理BuildConfig

这是我的某个项目中的示例build.gradle文件。

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

def keystorePropertiesFile = rootProject.file("../Path_To_KeyStore/keystore.properties")
def keystoreProperties = new Properties()
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))

def appPropertiesFile = rootProject.file("app-settings.properties")
def appProperties = new Properties()
appProperties.load(new FileInputStream(appPropertiesFile))

android {
    compileSdkVersion 27
    buildToolsVersion "27.0.3"

    signingConfigs {
        MyAppSigningConfig {
            keyAlias keystoreProperties['keyAlias']
            keyPassword keystoreProperties['keyPassword']
            storeFile file(keystoreProperties['storeFile'])
            storePassword keystoreProperties['storePassword']
        }
    }

    defaultConfig {
        applicationId "com.example.myapp"
        minSdkVersion 21
        targetSdkVersion 27
        versionCode appProperties['app.version.code'] as int
        versionName appProperties['app.version.name']
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        def buildVariant = getBuildVariant()
        def environmentPath
        if ((buildVariant == "Release")) {
            environmentPath = appProperties["env.path.live"]
        } else if ((buildVariant == "Debug")) {
            environmentPath = appProperties["env.path.test"]
        } else {
            environmentPath = appProperties["env.path.live"]
        }

        def envPropertiesFile = rootProject.file(environmentPath)
        def envProperties = new Properties()
        envProperties.load(new FileInputStream(envPropertiesFile))
        println("buildVariant = $buildVariant")
        for (String key : envProperties.keySet()) {
            buildConfigField "String", key.replaceAll("\\.", "_").toUpperCase(), envProperties[key]
        }
    }

    buildTypes {
        debug {
            applicationIdSuffix ".debug"
            manifestPlaceholders = [appName: "@string/app_name_debug_test"]
        }

        release {
            manifestPlaceholders = [appName: "@string/app_name"]
            signingConfig signingConfigs.MyAppSigningConfig
            minifyEnabled false
            multiDexEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

def getBuildVariant() {
    for (TaskExecutionRequest t : gradle.getStartParameter().getTaskRequests()) {
        for (String command : t.args) {
            if (command.matches(":app:generate(.*)Sources")) {
                return command.replaceAll(":app:generate(.*)Sources", "\$1")
            } else if (command.matches(":app:assemble(.*)")) {
                return command.replaceAll(":app:assemble(.*)", "\$1")
            }
        }
    }

    return "Release"
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:27.1.0'
    implementation 'com.android.support:recyclerview-v7:27.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

我在这里有两种不同的构建变体。一个是发布,另一个是调试。我在应用程序目录中有三个属性文件。这些如下。

app-settings.properties文件如下所示。

app.version.code=1
app.version.name=0.0.1
env.path.live=live-env.properties
env.path.test=test-env.properties

test-env.properties看起来像

base.url.auth="http://localhost:8888/auth/"
base.url.communication="http://localhost:8000/communication/"
base.url.site="http://localhost:8000/"
api.key.auth="demo_key"

live-env.properties就像

base.url.auth="http://auth.yourapp.com/auth/"
base.url.communication="http://yourapp.com/communication/"
base.url.site="http://yourapp.com/"
api.key.auth="live_key1223ssHHddSSYYY"

因此,一旦设置了build.gradle和应用程序属性,您就需要与gradle同步以生成BuildConfig.java文件。您将看到使用从属性文件中找到的值自动生成文件。

您可以从代码中的任何位置访问以下环境变量。

const val BASE_URL = BuildConfig.BASE_URL_SITE
const val BASE_URL_AUTH = BuildConfig.BASE_URL_AUTH

从Android Studio中的构建变体的左侧菜单中获取所需的应用程序构建。

enter image description here

我的一位名叫Sajid Shahriar的同事帮助我理解了不同构建变体的设置。因此,我与你分享这个。希望有所帮助。