I've managed to get Google Cloud Speech working for my Android app using a service account in streaming mode via GRPC. However, according to what I've read, I shouldn't deploy an Android app with these credentials in them (currently stored as a JSON file in a resource) for security reasons. The correct thing is to create an API key, as described here: https://cloud.google.com/speech/docs/common/auth
This allows me to restrict access to my specific Android app. However, I have been unable to find out how to use the API Key from GRPC. I'm currently creating a GoogleCredentials
instance from the JSON file, and this works fine. How can I get a credentials object from the API Key?
you can try this with the API key
Metadata.Key<String> API_KEY = Metadata.Key.of("x-goog-api-key", Metadata.ASCII_STRING_MARSHALLER);
Metadata apiKeyMetadata = new Metadata();
apiKeyMetadata.put(API_KEY, yourApiKey);
final ManagedChannel channel = new OkHttpChannelProvider()
.builderForAddress(HOSTNAME, PORT)
.nameResolverFactory(new DnsNameResolverProvider())
.intercept(MetadataUtils.newAttachHeadersInterceptor(apiKeyMetadata))
.build();
speechStub = SpeechGrpc.newStub(channel);
I cannot find any Android example. However, the sample iOS client sets up a gRPC connection using the API key. It puts the key in the request header. You can try translating the iOS code into Android.
https://github.com/GoogleCloudPlatform/ios-docs-samples/blob/master/speech/Objective-C/Speech-gRPC-Streaming/Speech/SpeechRecognitionService.m#L59
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With