The Application Default Credentials Are Not Available
I am trying to use speech-to-text API of Google Cloud Platform for my Android App. I have passed it a recorded audio file for conversion to text. I can't solve an IOException whic
Solution 1:
GOOGLE_APPLICATION_CREDENTIALS is a compile time variable. you can notice there is task in the build.gradle that copies the credentials from where ever the variable points to to the credential.json file in the raw directory:
task copySecretKey(type: Copy) {
def File secretKey = file "$System.env.GOOGLE_APPLICATION_CREDENTIALS"from secretKey.getParent()
include secretKey.getName()
into 'src/main/res/raw'
rename secretKey.getName(), "credential.json"
}
this file should then be addressed in code to produce an access token for the API services:
privateclassAccessTokenTaskextendsAsyncTask<Void, Void, AccessToken> {
@Overrideprotected AccessToken doInBackground(Void... voids) {
finalSharedPreferencesprefs=
getSharedPreferences(PREFS, Context.MODE_PRIVATE);
StringtokenValue= prefs.getString(PREF_ACCESS_TOKEN_VALUE, null);
longexpirationTime= prefs.getLong(PREF_ACCESS_TOKEN_EXPIRATION_TIME, -1);
// Check if the current token is still valid for a whileif (tokenValue != null && expirationTime > 0) {
if (expirationTime
> System.currentTimeMillis() + ACCESS_TOKEN_EXPIRATION_TOLERANCE) {
returnnewAccessToken(tokenValue, newDate(expirationTime));
}
}
// ***** WARNING *****// In this sample, we load the credential from a JSON file stored in a raw resource// folder of this client app. You should never do this in your app. Instead, store// the file in your server and obtain an access token from there.// *******************finalInputStreamstream= getResources().openRawResource(R.raw.credential);
try {
finalGoogleCredentialscredentials= GoogleCredentials.fromStream(stream)
.createScoped(SCOPE);
finalAccessTokentoken= credentials.refreshAccessToken();
prefs.edit()
.putString(PREF_ACCESS_TOKEN_VALUE, token.getTokenValue())
.putLong(PREF_ACCESS_TOKEN_EXPIRATION_TIME,
token.getExpirationTime().getTime())
.apply();
return token;
} catch (IOException e) {
Log.e(TAG, "Failed to obtain access token.", e);
}
returnnull;
}
@OverrideprotectedvoidonPostExecute(AccessToken accessToken) {
mAccessTokenTask = null;
finalManagedChannelchannel=newOkHttpChannelProvider()
.builderForAddress(HOSTNAME, PORT)
.nameResolverFactory(newDnsNameResolverProvider())
.intercept(newGoogleCredentialsInterceptor(newGoogleCredentials(accessToken)
.createScoped(SCOPE)))
.build();
mApi = SpeechGrpc.newStub(channel);
// Schedule access token refresh before it expiresif (mHandler != null) {
mHandler.postDelayed(mFetchAccessTokenRunnable,
Math.max(accessToken.getExpirationTime().getTime()
- System.currentTimeMillis()
- ACCESS_TOKEN_FETCH_MARGIN, ACCESS_TOKEN_EXPIRATION_TOLERANCE));
}
}
}
Post a Comment for "The Application Default Credentials Are Not Available"