Following the gRPC announcement for Cloud PubSub, this Android sample publishes into a topic, and pulls messages fom a subscription. It takes some guidelines from here. The code can be executed on an Android device.
1) Android Studio
2) Gradle 2.12
3) Android plugin for gradle
4) Protobuf plugin for gradle 0.7.7
Important to have Gradle and the protobuf plugin exactly in the versions above (2.12 and 0.7.7 respectively). protoc must be in version 3. 7
The following dependency needs to be added to build.gradle:
compile 'com.google.api.grpc:grpc-pubsub-v1:0.0.2'
Authentications using gloud-java libraries are described here. Remember to set prereqs and enable PubSub API on your Google Cloud project.
Basically you have two authentication options from Android:
AssetManager am = mContext.getAssets();
InputStream isCredentialsFile = am.open( YOUR_JSON_FILE_INSIDE_ASSETS_DIRECTORY );
GoogleCredentials credential = GoogleCredentials.fromStream(isCredentialsFile);
credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/pubsub"));
String scopesString = "https://www.googleapis.com/auth/pubsub";
String SCOPE = "oauth2:" + scopesString;
token = GoogleAuthUtil.getToken(
mContext, // Context of your Main activity
mAccount, // Account name with permissions to PubSub and your cloud proyect
SCOPE // String scope
);
GoogleCredentials credential = new GoogleCredentials( new AccessToken( token, null) );
credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/pubsub"));
By default, the protobuf plugin for gradle always uses javanano implementation in Android. Pubsub.proto uses proto3 built-in types (empty.proto and annotations.proto) which are not included on the javanano implementation. This is properly handled by the plugin, however, it causes some duplicated dependencies which needed to be resolved by excluding the duplications on the packagingOptions block on build.gradle
Main activity: