Search code examples
androidpubnub

How to receive a push notification in PubNub Android ???


What will be the broadcast receiver to receive a push notification in pubnub android.


Solution

  • PubNub released a blog post that fully covers sending and receiving GCM with their Android SDK.

    Sending and Receiving Android Push Notifications w/ GCM

    To summarize, the receiver and intent filter should look as follows:

    <receiver android:name=".GcmBroadcastReceiver" 
              android:permission="com.google.android.c2dm.permission.SEND" > 
        <intent-filter> 
            <action android:name="com.google.android.c2dm.intent.RECEIVE" /> 
            <category android:name="your.package.name" /> 
        </intent-filter> 
    </receiver> 
    <service android:name=".GcmIntentService" /> 
    <meta-data android:name="com.google.android.gms.version" 
               android:value="@integer/google_play_services_version" /> 
    

    And your GcmBroadcastReceiver should look something like this:

    public class GcmBroadcastReceiver extends WakefulBroadcastReceiver { 
        @Override 
        public void onReceive(Context context, Intent intent) { 
            ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName()); 
            startWakefulService(context, (intent.setComponent(comp))); 
            setResultCode(Activity.RESULT_OK); 
        } 
    }
    

    And finally, the GcmIntentService:

    public class GcmIntentService extends IntentService {   
        public GcmIntentService() { 
            super("GcmIntentService"); 
        }   
    
        @Override protected void onHandleIntent(Intent intent) { 
            Bundle extras = intent.getExtras(); 
            GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); 
            String messageType = gcm.getMessageType(intent);   
            if (!extras.isEmpty() && GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE) {
                sendNotification("Received: " + extras.toString()); 
            } 
            GcmBroadcastReceiver.completeWakefulIntent(intent); 
        }
        ...
    }
    

    If there is anything that I am not covering that you wish to see, check the blog. If you do not see it there or are still having trouble let me know and I would be glad to elaborate on anything PubNub GCM related for you!