rafaelsf80 / cloud-pubsub-grpc-android

Sample app to access to Cloud PubSub (gRPC) from an Android device
4 stars 6 forks source link

Cloud PubSub (gRPC) with Android

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.

Setup

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

PubSub gRPC dependencies

The following dependency needs to be added to build.gradle:

compile 'com.google.api.grpc:grpc-pubsub-v1:0.0.2'

Authentication

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"));

Java protobuf nano implementation with 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

Screenshots

Main activity:

alt text alt text