Android - 从 github 中排除 api 密钥,在代码中将 api 密钥存储在哪里?

问题描述 投票:0回答:5

我想知道在 android studio 中存储 api 密钥的最佳方式是什么。我想使用 gitignore 从 github 中排除这个文件。

我看到有些人在 HOME 目录中使用 gradle.properties,但 api 是特定于我的应用程序的。

我还注意到新的 android studio 项目中有一个 gradle.properties,但这可能包含我可能不想排除的其他内容。

有人知道最好的方法吗?

因此该文件将在本地可用,我的项目将在运行时读取它,但我“可能”会忽略该文件,这样我就不会提交它,这样我就不会公开我的 api 密钥。

android android-gradle-plugin
5个回答
3
投票

我看到有些人在 HOME 目录中使用 gradle.properties,但 api 是特定于我的应用程序的。

我认为 API 特定于您的应用程序没有问题。有时我们也会遇到类似的情况,所以我们只是为

gradle.properties
条目使用一些唯一的名称。类似的东西

(MY_APP_NAME)_(MY_API_NAME)_API_KEY

此外,我们还以相同的方式将密码存储到内部 Maven 存储库,因此它们不会作为

build.gradle
文件的一部分推送到 GitHub。我可以说我们对这种方法非常满意。

我可以考虑的一些替代方案:

  • 执行任务时显式传递参数给gradle。因此,您可以将这些参数存储在 Android Studio 配置中。
  • 您可以使用
    .gradle
    将另一个
    apply from: 'path-to-my-local-script.gradle'
    文件应用到您的构建脚本(其中将包含您的变量)。只是不要忘记将其添加到
    .gitignore

3
投票

您可以借助 gradle 和系统路径变量来存储 api 密钥 添加新的系统路径变量 THE_MOVIE_DB_API_TOKEN="XXXXX":

对于 Windows 操作系统:

  • 打开系统
  • 高级系统设置
  • 环境变量
  • 向用户变量添加新变量

将以下代码添加到build.gradle文件中

apply plugin: 'com.android.application'

  android {
   ...

    defaultConfig {
        ...
    }
    buildTypes {
        release {
            ...
        }
        buildTypes.each {
            it.buildConfigField 'String', 'THE_MOVIE_DB_API_TOKEN', "$System.env.THE_MOVIE_DB_API_TOKEN"
        }
    }
}

像这样在 Java 代码中使用 API 密钥

BuildConfig.THE_MOVIE_DB_API_TOKEN)


3
投票

在 MacOS 上将其放入

~/.gradle/gradle.properties

THE_MOVIE_DATABASE_API_KEY=***********

Android Studio Gradle int build.gradle

    defaultConfig {
    applicationId "com.sample"
    minSdkVersion 16
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    buildConfigField "String" , "API_KEY" ,  "\"$THE_MOVIE_DATABASE_API_KEY\""
}

然后在Java代码中您可以访问

BuildConfig.API_KEY


0
投票

您可以在

local.properties
中定义它,这通常不受源代码控制:

apikey="sdkjhqsffoief"

您的

build.gradle
应如下所示:

android {
    //…
    // Load properties file containing our API key
    Properties properties = new Properties()
    properties.load(project.rootProject.file('local.properties').newDataInputStream())
    def apikey = properties.getProperty('apikey')

    defaultConfig {
        //…
        buildConfigField "String" , "API_KEY" ,  apikey

    }

    buildFeatures {
        //…
        buildConfig true
    }
}

在代码中你可以这样访问它:

val apiKey = BuildConfig.API_KEY

0
投票

如果我的 local.properties 不受版本控制,那么当用户从 Play 商店下载应用程序时如何访问这些文件。

© www.soinside.com 2019 - 2024. All rights reserved.