Android集成Google翻译API遇密钥缺失错误及环境变量问题求助
Hey there! Let's tackle your problem from two angles: fixing the missing API key error first, then explaining those mysterious environment variables you're seeing.
一、解决"The request is missing a valid API key"错误
First off, the core issue here is that Android emulators/real devices don't access your Windows system environment variables—they run their own independent Android OS, so those variables you set on Windows are invisible to your app. Here's how to properly configure your API key:
Get a properly restricted API key from GCP Console
- Go to your GCP project, navigate to "APIs & Services" > "Credentials"
- Create an API key, then set restrictions to "Android apps" (enter your app's package name and SHA-1 fingerprint for security—you can get the emulator's SHA-1 from Android Studio's "Signing Report" under Gradle > Tasks > android > signingReport)
Add the API key to your Android project
- Avoid hardcoding the key directly in your code. Instead, add it to
res/values/strings.xml:<string name="google_translate_api_key" translatable="false">YOUR_API_KEY_HERE</string> - Initialize the Translate service in your code using this key:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String apiKey = getString(R.string.google_translate_api_key); Translate translate = TranslateOptions.newBuilder() .setApiKey(apiKey) .build() .getService(); // Rest of your translation logic... }
- Avoid hardcoding the key directly in your code. Instead, add it to
Double-check API enablement
- Confirm the Google Cloud Translation API is enabled in your GCP project (go to "APIs & Services" > "Library" and search for it)
二、那些环境变量来自哪里?
When you call System.getProperties() in your Android app, the variables you see (SYSTEMSERVERCLASSPATH, ANDROID_STORAGE, PATH etc.) are system-level environment variables from the Android emulator's OS, not your Windows system.
Android is built on a Linux kernel, and the emulator runs a full Android system image. These variables are set during the emulator's boot process to manage system services, storage access, process execution paths, and other low-level OS functions. They have no connection to the environment variables you configured on your Windows machine.
额外小提示
If you're already using Firebase, consider checking out Firebase ML Kit Translation—it's designed specifically for mobile apps, integrates seamlessly with Firebase, and eliminates the need to manage separate GCP API keys (though it's totally optional if you prefer the standard Cloud Translation API).
内容的提问来源于stack exchange,提问作者Danny T




