Android应用RAW目录存JSON凭证仍提示默认凭证不可用问题
Let’s break down exactly what’s going wrong here:
1. You’re Using the Wrong Method to Load Service Account Credentials
The GoogleCredential.FromJson(json) method isn’t designed to parse raw service account JSON files. It’s meant to deserialize a pre-serialized GoogleCredential object (i.e., JSON that was generated by serializing an existing GoogleCredential instance).
Your service account JSON has a specific structure (with fields like "type": "service_account", "client_email", "private_key", etc.) that FromJson() doesn’t recognize. When this method fails to create a valid credential, the library falls back to trying to load Application Default Credentials (ADC)—which don’t exist in a typical Android environment—hence the error you’re seeing.
2. Correct Approach to Load Service Account Credentials on Android
Instead of FromJson(), you need to use the credential stream loader that’s built to handle service account JSON files. Here’s how to fix your code:
// Get input stream from your RAW directory credential file InputStream credStream = getResources().openRawResource(R.raw.your_service_account_json); // Load credentials from the stream, add required scopes GoogleCredentials credentials = GoogleCredentials.fromStream(credStream) .createScoped(Arrays.asList("https://www.googleapis.com/auth/your_target_scope")); // If you specifically need a GoogleCredential object (for older API compatibility) GoogleCredential googleCredential = ((ServiceAccountCredentials) credentials).toBuilder() .build();
This method properly parses the service account JSON structure and initializes the credential correctly, avoiding the fallback to ADC.
内容的提问来源于stack exchange,提问作者Pablo

