I have created a GCM Intent service and the device is getting registered successfully and server successfully send the message. but device don't get any notifications.
Below the log i see,
10-29 18:26:09.599: V/GCMBroadcastReceiver(30775): onReceive: com.google.android.c2dm.intent.RECEIVE
10-29 18:26:09.599: V/GCMBroadcastReceiver(30775): GCM IntentService class: com.eye.hor.GCMIntentService
10-29 18:26:09.599: V/GCMBaseIntentService(30775): Acquiring wakelock
Below is the code for GCMBroadcastReceiver,
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i(context.getPackageName(), intent.getExtras().toString());
Log.d("brdR", "askd");
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
Below is the code for GCMIntentService,
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that
* GCM will be extended in the future with new message types, just
* ignore any message types you're not interested in, or that you
* don't recognize.
*/
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
// sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
// sendNotification("Deleted messages on server: " +
// extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// This loop represents the service doing some work.
// for (int i = 0; i < 5; i++) {
// Log.d("", "Working... " + (i + 1) + "/5 # " +
// SystemClock.elapsedRealtime());
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// }
// }
Log.d("true", "Completed work # " + SystemClock.elapsedRealtime());
// Post notification of received message.
sendNotification(extras.getString("msg"), extras.getString("title"), extras.getString("id"));
Log.d("true", "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg, String title, String id) {
mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
int notification_id = Integer.parseInt(id);
// PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new
// Intent(this, CommonUtils.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.icon).setContentTitle(title)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg);
// mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(notification_id, mBuilder.build());
}
}
This is manifest,
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Creates a custom permission so only this app can receive its messages. -->
<permission
android:name="com.eye.hor.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.eye.hor.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- Permission to vibrate -->
<uses-permission android:name="android.permission.VIBRATE" />
Receiver Code in Manifest,
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.eye.hor.service" />
</intent-filter>
</receiver>
<service android:name="com.eye.hor.service.GCMIntentService" />
My main package name is com.eye.hor but i placed GCMIntentService and GCMBroadcastReceiver java files in the com.eye.hor.service package. i already put log in these two classes but they not reach.
please help
Looks like you already know you have a problem with the package names :
The following looks for your service class in the wrong package :
ComponentName comp =
new ComponentName(context.getPackageName(), // this is the main package of
// your app - com.eye.hor
GcmIntentService.class.getName());
Change it to :
ComponentName comp =
new ComponentName(GcmIntentService.class.getPackage().getName(),
GcmIntentService.class.getName());
You should also change the category in your manifest to the main package :
<category android:name="com.eye.hor.service" />
to
<category android:name="com.eye.hor" />
<category android:name="com.eye.hor.service" />
This is not supposed to be the package your broadcastreceiver is in, this is the package defined in the google developers console.
I'm willing to bet in your google developers console you defined the package has com.eye.hor, in which case you would have to change this line to:
<category android:name="com.eye.hor" />
What is device on which you developed your app? On different devices there are exotic settings influence on background working, check such setting in your device ("autostart", "push notification" and other, they can called different on some devices like Xiamo, Huawei and other).
Are you sure that your push server uses correct "sender id" and "api key" parameters, which you can check in developer console?
Check that Google Play services installed correct.
Related
I can receive push notification when my app is in foreground or background
I added FcmBroadcastReceiver extends WakefulBroadcastReceiver in order to get push
when I close my application.
But I continue without receiving notifications when the app is closed.
Thanks for your help.
manifest.xml
<pre>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="<package>.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.package.name.permission.C2D_MESSAGE" />
<receiver
android:name="<package>.Notification.FcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="<package>" />
</intent-filter>
</receiver>
<service android:name=".Notification.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
public class FcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("receiver","okey");
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
MyFirebaseMessagingService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
public class MyFirebaseMessagingService extends FirebaseMessagingService {
Intent i;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
System.out.println("******************** + getMessageType "+remoteMessage.getMessageType());
System.out.println("******************** + getFrom "+remoteMessage.getFrom());
System.out.println("******************** + getMessageId "+remoteMessage.getMessageId());
System.out.println("******************** + getTo "+remoteMessage.getTo());
System.out.println("******************** + getData "+remoteMessage.getData());
System.out.println("******************** + getData().get(message) "+remoteMessage.getData().get("message"));
System.out.println("******************** + getData().get(title) "+remoteMessage.getData().get("title"));
showNotification(remoteMessage.getData().get("type"),remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
}
private void showNotification(String to , String title, String message) {
i = new Intent(this,ProfileActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i, PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentTitle(title)
.setContentText(message)
.setSound(defaultSoundUri)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0,builder.build());
}
}
<code>
The issue that I can see in your code is that you are implementing the FireBase push notification but you are trying to implement that in a way that was used to implement GCM. You don't need to set any Broadcast Receivers, Firebase is doing that by itself. You just have to run "FirebaseMessagingService". The services looks like this:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO: Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated.
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
}
}
As you can see it has it's own "onMessageReceived" method that takes care of Broadcast Receiver's functionality.
Check this tutorial, it will help you to understand:
https://www.codementor.io/flame3/send-push-notifications-to-android-with-firebase-du10860kb
Note: If you want your app to work in each situation even app is in background, foreground or even closed then you need to send some data through payload in your notification.then it will work for all conditions. To do that you need your own server, Firebase doesn't facilitate for that.
My GCM Service is not working. I have declared a few things in my manifest file which looks something like:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.google.android.c2dm.permission.SEND"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<permission android:name="com.xxxx.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="com.xxxx.xxxxxx.permission.C2D_MESSAGE" />
<receiver android:name=".core.push.receiver.GCMBroadcastReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.SEND" />
<category android:name="com.xxxx.xxxxxx" />
</intent-filter>
</receiver>
<service android:name=".core.push.service.GCMIntentService" />
My Broadcast receiver code looks like:
public class GCMBroadcastReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
ComponentName messageProcessingService = new ComponentName(context.getPackageName(), GCMIntentService.class.getName());
context.startService(intent.setComponent(messageProcessingService));
setResultCode(Activity.RESULT_OK);
}
}
My Intent Service:
public class GCMIntentService extends IntentService
{
private static final int NOTIFICATION_NEW_MESSAGE = 0;
public GCMIntentService()
{
super(GCMIntentService.class.getSimpleName());
}
#Override
protected void onHandleIntent(Intent intent)
{
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty())
{
if (!GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType))
{
return;
}
// TODO Make more efficient. Load message stream here, not in two places later!
int newUnreadCount = MessagingController.getInstance().getUnreadCount() + 1;
MessagingController.getInstance().prepareStream();
MessagingController.getInstance().setUnreadCount(newUnreadCount);
final boolean isUserAuthenticated = !TextUtils.isEmpty(AuthenticationController.getInstance().getAuthToken());
if (isUserAuthenticated)
{
new Handler(Looper.getMainLooper()).post(new Runnable()
{
#Override
public void run()
{
App.from(GCMIntentService.this).fire(MessagingEvent.NEW_MESSAGE);
}
});
}
else
{
displayNotification(newUnreadCount + " New Message" + (newUnreadCount > 1 ? "s" : ""), newUnreadCount);
}
}
}
private void displayNotification(CharSequence message, int eventCount)
{
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean shouldDisplayMessages = preferences.getBoolean("notifications_new_message", true);
if (!shouldDisplayMessages)
{
return;
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent openMessagingScreen = new Intent(this, LandingActivity.class);
openMessagingScreen.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
openMessagingScreen.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
preferences.edit().putBoolean(MessagingFragment.PREF_MESSAGE_WAITING, true).apply();
PendingIntent notificationAction = PendingIntent.getActivity(this, 0, openMessagingScreen, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(getString(R.string.app_name))
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setContentText(message)
.setAutoCancel(true)
.setContentIntent(notificationAction)
.setNumber(eventCount);
Notification notification = notificationBuilder.build();
notification.defaults |= Notification.DEFAULT_ALL;
try
{
notificationManager.notify(NOTIFICATION_NEW_MESSAGE, notification);
}
catch (SecurityException ex)
{
// This is required due to a bug in android
// http://stackoverflow.com/questions/13602190/java-lang-securityexception-requires-vibrate-permission-on-jelly-bean-4-2
Log.e("PPDirect", ex.getLocalizedMessage());
}
}
}
I had several questions regarding push notifications:
which call back function actually checks for arrived message and is called once push notification arrives?
Is it possible that since google have updated GCM to FCM I need to make updates to the key or migrate GCM to FCM?
Can there be some other reason?
Any help in the matter would be much appreciated.
1. which call back function actually checks for arrived message and is called once push notification arrives?
For Android, it's commonly received in onMessageReceived in the GcmListenerService. However, it may also depend whether or not the app is in background or foreground.
2. Is it possible that since google have updated GCM to FCM I need to make updates to the key or migrate GCM to FCM?
As per the note here:
Starting from Sept. 2016 new server key can only be created in the Firebase Console using the Cloud Messaging tab of the Settings panel. Existing projects that need to create a new server key can be imported in the Firebase console without affecting their existing configuration.
New users of GCM is in need of creating a Firebase projext, regardless if you are going to use FCM or not, in order to have a Server Key. For the migration steps, you can see my answer here.
3. Can there be some other reason?
This is too broad to answer. Maybe it's because of your payload structure or the implementation of your onMessageReceived(), etc.
We have implemented GCM to show notifications in android application but only some messages not receiving in devices sent by server to google? Server is sending messages without collapse_key so every message should reach in device without collapsed. Please suggest me to proceed further.
Thanks
Receiver code is below:
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
service code is below:
public class GcmIntentService extends IntentService {
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
public static final String TAG = "GCM Demo";
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM will be
* extended in the future with new message types, just ignore any message types you're
* not interested in, or that you don't recognize.
*/
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
//sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
//sendNotification("Deleted messages on server: " + extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// This loop represents the service doing some work.
for (int i = 0; i < 5; i++) {
Log.i(TAG, "Working... " + (i + 1)
+ "/5 # " + SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
generateNotification(this, name, id, message);
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
}
Manifest file is below
<permission
android:name="MY_PACKAGE_NAME.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="MY_PACKAGE_NAME.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<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="MY_PACKAGE_NAME" />
</intent-filter>
</receiver>
<service android:name=".GcmIntentService" />
You need to create a Google account in that device (Settings -> Accounts -> Google). So please check whether it's logged with Google or not :)
When I send a push notification to the emulator I get this message:
{"multicast_id":8595716062607030073,"success":1,"failure":0,"canonical_ids":1,"results": [{"message_id":"0:1403002114354553%44f16b55f9fd7ecd","registration_id":"XXXXXXX...
But after registering and sending the notification to my device with the new regId i get this :
{"multicast_id":8356469968000736599,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1403002260325568%44f16b55f9fd7ecd"}]}
I activated the notification in my phone and connected with Google account
Also i get the new registration ID in my database when registering but i cant figure out the problem
Here is my manifest.xml:
<!-- for gcm -->
<receiver
android:name="com.test.android.gcm.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.test.android.gcm" />
</intent-filter>
</receiver>
<service android:name="com.test.android.gcm.GCMNotificationIntentService" />
<!-- end for gcm -->
<!-- GCM activity -->
<activity
android:name="com.test.android.gcm.RegisterActivity"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.test.android.gcm.MainActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name" >
</activity>
<!-- End GCM activity -->
Can anyone point me to the right direction please
This is how it works.
When registering a client to GCM you get a registration ID. Let's call it A. Your server will hold on to that for it to be able to send notifications.
Time goes by and for whatever reason, say expiration of the registration ID in the GCM server, GCM decides to give the same client a different, newer ID. We'll call it B. Your server holds on to that one, too.
Now you have to IDs for the same device, one is old and another is up to date. They will both be valid for sending notifications.
In a MulticastResult, receiving a Canonical ID means that the ID you're using isn't the most recent ID. When you do receive a canonical ID, it should replace the one you're using (since it's the most up to date ID).
For A you'll receive a MulticastResult with success=1, canonical id=B. For B you'll just receive success=1 because it is the most recent ID. The response for A indicates it is out of date and should be replace by B.
Since in your case you're using a newly registered ID (like you've said), there's no reason for it to be out of date, and there is no problem with your code.
As for why you are not getting the notification, your client has to have a receiver class that extends WakefulBroadcastReceiver, and handles the incoming notification:
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
and an IntentService to complete the picture
`public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM
* will be extended in the future with new message types, just ignore
* any message types you're not interested in, or that you don't
* recognize.
*/
if (GoogleCloudMessaging.
MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " +
extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// This loop represents the service doing some work.
for (int i=0; i<5; i++) {
Log.i(TAG, "Working... " + (i+1)
+ "/5 # " + SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
Log.i(TAG, "Completed work # " + SystemClock.elapsedRealtime());
// Post notification of received message.
sendNotification("Received: " + extras.toString());
Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, DemoActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_gcm)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
See Implementing a GCM client.
Does anybody can help me with a working example for receiving messages from gcm using Google Cloud Messaging for Android. I have tried both ways (helper library and GoogleCloudMessaging class) and nothing seems to work. I'm using a PHP script that shows the following:
Multicast ID: 5.2108110103215E+18
Number of messages processed successfully: 1
Number of messages with processing errors: 0
Canonical IDs: 0
So apparently everithing is OK. I could register the device in both ways, using the helper library (gcm.jar) and using GoogleCloudMessaging class. The problem is that there is no way the message I send via PHP arrives, or at least I don't know how to handle it correctly. Here are the permissions and the receiver from my manifest:
<permission android:name="com.example.gcm.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<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.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.READ_OWNER_DATA" />
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.example.gcm" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
Finally here is the service class
public class GCMIntentService extends GCMBaseIntentService {
private static final String PROJECT_ID = "49XXXXXXXX6";
private static final String TAG = "GCM Intent Service";
public GCMIntentService()
{
super(PROJECT_ID);
Log.d(TAG, "GCMIntentService init");
}
#Override
protected void onError(Context ctx, String sError) {
Log.d(TAG, "Error: " + sError);
}
#Override
protected void onMessage(Context ctx, Intent intent) {
Log.d(TAG, "Message Received");
String message = intent.getStringExtra("message");
sendGCMIntent(ctx, message);
}
private void sendGCMIntent(Context ctx, String message) {
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("GCM_RECEIVED_ACTION");
broadcastIntent.putExtra("gcm", message);
ctx.sendBroadcast(broadcastIntent);
}
#Override
protected void onRegistered(Context ctx, String regId) {
Log.d(TAG, regId);
// Notify main UI to update registration status
Intent registrationIntent = new Intent();
registrationIntent.setAction("registered");
registrationIntent.putExtra("regId", regId);
sendBroadcast(registrationIntent);
}
#Override
protected void onUnregistered(Context ctx, String regId) {
//...
}
}
Here is the code when using the GoogleCloudMessaging class (I changed the manifest to use the custom receiver):
public class GCMBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "GCM Receiver";
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
private Context ctx;
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Message received");
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
ctx = context;
String messageType = gcm.getMessageType(intent);
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + intent.getExtras().toString());
}
else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)) {
sendNotification("Deleted messages on server: "
+ intent.getExtras().toString());
}
else {
sendNotification("Received: " + intent.getExtras().toString());
}
setResultCode(Activity.RESULT_OK);
}
// Put the GCM message into a notification and post it.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager) ctx
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
new Intent(ctx, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
ctx).setSmallIcon(R.drawable.ic_launcher_temp)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
The thing is that everything seems to be ok, but the message never arrives. Any ideas??
Thanks in advance.
Add the following in your manifeast
<permission
android:name="PACKAGE_NAME.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="PACKAGE_NAME.permission.C2D_MESSAGE" />
<!-- App receives GCM messages. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
Your manifest is missing some permissions :
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="com.example.gcm.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />
EDIT :
In your manifest you are using com.google.android.gcm.GCMBroadcastReceiver. That's a class from the old helper library (gcm.jar) which starts an intent service. If you want to use the helper library you should define the intent service in your manifest.
If you don't want to use the helper library, you should change the package of GCMBroadcastReceiver in the manifest to be the package of the GCMBroadcastReceiver class that you included in your question. Otherwise, that class won't be used.
After correcting the issues above still no push messages. The problem was the 403 error. Looks like that service is not available in Cuba, so the solution is to use a tool like "your freedom" or "thor", etc.
Don't forget to change 'com.example.gcm' to your package name e.g. 'com.yourdomain.yourapp'
You are using GCMBaseIntentService which has been deprecated by Google. (But it should be still working.) I followed the latest tutorial http://developer.android.com/google/gcm/client.html and did receive messages. You can try it too.
Another possible reason is you may have received a message but it was not shown in a notification successfully. Add this line in the method: sendNotification(String msg)
Log.i(TAG, msg);