Search code examples
androidpush-notificationbroadcastreceivergoogle-cloud-messaging

new Google Cloud Messaging API


I'm sending a push notification using PHP using curl, and the result seems to return fine:

{"multicast_id":2345735671345346,"success":2,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:13456457587969%375ed23445237ecd"},{"message_id":"0:12344526107806%375ed3439fd7ecd"}]}

So I'm guessing the message is sent, and the problem is on the BroadcastReceiver subclass.

My Broadcast receiver code:

package com.example.myexample.pushnotifications;

public class GCMBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
        Log.d(TAG, "onReceive method executed properly");

        //NotificationManager and NotificationCompat.Builder code to build a notification
    }
}

then my AndroidManifest.xml for the permissions:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" /
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission
    android:name="com.example.myexample.pushnotifications.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
<uses-permission android:name="com.example.myexample.pushnotifications.permission.C2D_MESSAGE" />

and for the receiver inside the application tag:

    <receiver
        android:name="com.example.myexample.pushnotifications.GCMBroadcastReceiver"
        android:enabled="true"
        android:exported="true"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="com.example.myexample.pushnotifications" />
        </intent-filter>
    </receiver>

The problem is that the broadcast receiver never receives the message.


Solution

  • Assuming the package of the app is com.example.myexample, the following changes are required :

    <permission
        android:name="com.example.myexample.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.example.myexample.permission.C2D_MESSAGE" />
    
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <category android:name="com.example.myexample" />
    </intent-filter>