Friday 4 December 2015

Handling GCM Push Notifications in Android Flavors

In Android Flavors generally we have different package names in our single app for flavours.

When implementing GCM Push Notifications in our android app in case of Flavors there is very little thing that we need to do differently.

Since our Package Name i.e application id is going to be different for different Flavors then push notifications going to be a problem in that case.

Below is the permissions that we generally declare in manifest file when using GCM.
   

 <!-- GCM requires a Google account. -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />

    <!-- Creates a custom permission so only this app can receive its messages. -->
    <permission
        android:name="yourpackagename.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="yourpackagename.permission.C2D_MESSAGE" />

    <!-- This app has permission to register and receive data message. -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
   
   
    Now suppose if we are implementing flavours then way of defining these permissions will change.
    Suppose we have below flavours in our build.gradle.
   
    productFlavors {
                        paid
                    {
                        applicationId "com.example.paid"
                        versionCode 1
                        versionName "1.0"
                    }
                        free
                    {
                        applicationId "com.example.free"
                        versionCode 1
                        versionName "1.0"
                    }
                }
               
           
Now when running GCM according to different variants will be a problem. GCM will work accordingly whose permission with package name is defined in manifest.

So add runtime Package Name to the manifest permissions in case of Android Flavors. Below is how can we declare single permissions for multiple Android Flavors in android manifest file.
   
   

    <!-- GCM notifications permissions-->


    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />

    

    <permission android:name="${applicationId}.permission.C2D_MESSAGE"

        android:protectionLevel="signature" />

    

    <uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />

    
   
Here ${applicationId} will be replaced by the applicationId of the running build variant defined in build.gradle of the app.


Cheers!!

No comments:

Post a Comment