I'm having an issue with Firebase notifications. I set up it as the docs but it's not working. Below, you can see my code. Although I think everything is right.
Here's my NotificationsService
public class NotificationsService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String TAG = "Notification";
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
}
And the AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.usefashion.useapp">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.NoActionBar">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".NotificationsService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".InstanceIdService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
</application>
</manifest>
It would be great if anyone could help me. I have an InstanceIdService too but its not the part of this question.
Edit 1:
I realized that when I send a notification by console, this message is showed in debug:
E/FirebaseInstanceId: Error resolving target intent service, skipping classname enforcement. Resolved service was: com.taplane.triviaquiz/com.msi.logocore.helpers.thirdparty.firebase.FirebaseServiceListener
What is it?
hers's my fcm services:
=> public class MyFirebaseInstanceIdServices extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
#Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "FireBase token: " + refreshedToken);
Prefs.setFirebaseToken(getApplicationContext(), refreshedToken);
}
}
=> public class MyFirebaseMessagingServices extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getData() + " Message Body");
Map<String, String> notiMessage = remoteMessage.getData();
String type = notiMessage.get("type");
String title = notiMessage.get("title");
String message = notiMessage.get("message");
String orderId = notiMessage.get("order_id");
sendNotification(type, title, message, orderId);
}
//This method is only generating push notification
private void sendNotification(String type, String title, String message, String orderId) {
if (Prefs.getIsLogin(this)) {
Intent intent = null;
if (type.equals("order")) {
intent = new Intent(this, OrderConfirmationActivity.class);
intent.putExtra(Constant.ORDER_ID, orderId);
intent.putExtra("FromNoti", true);
} else {
intent = new Intent(this, HomeActivity.class);
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_marker);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(bitmap)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
}
=> In Manifest file:
<service android:name="com.labagel.fcm.MyFirebaseMessagingServices">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name="com.labagel.fcm.MyFirebaseInstanceIdServices">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
Related
I send push notification to android phone.
Almost phones are receive and show notification except one phone(Samsung Galaxy Note 5).
The phone shows notification icon and goes at the same time.
You can see this issue followed url (refer 7sec and 22sec):
https://youtu.be/J6UZm_6mqP0
Here is AndroidMenifest.xml of my app
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_stat_notification" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id" />
<activity
android:name=".MainActivity"
android:configChanges="keyboard|keyboardHidden|orientation|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".FCMInstanceService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name=".MyFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
Where do i start to solve for this problem?
--More--
MyFirebaseMessagingService.java
package com.smartivt.smartivtmessenger;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.firebase.messaging.RemoteMessage;
import java.util.List;
public class MyFirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
private static final String TAG = "FirebaseMessaging";
private final String CHANNEL_ID = "DEFAULT_CHANNEL";
private final String CHANNEL_NAME = "Default Channel";
private final String GROUP_NAME = "MESSAGE_GROUP";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
NotificationManager notiMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if ( remoteMessage.getData().get("title") != null ) {
Log.d(TAG, "onMessageReceived: " + remoteMessage.getData().get("title"));
Log.d(TAG, "onMessageReceived: " + remoteMessage.getData().get("body"));
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ) {
Notification.Builder notify = new Notification.Builder(getApplicationContext(), CHANNEL_ID);
notify.setSmallIcon(R.drawable.ic_stat_notification);
notify.setContentTitle(remoteMessage.getData().get("title"));
notify.setContentText(remoteMessage.getData().get("body"));
notify.setAutoCancel(true);
notiMgr.notify(NotificationID.getID(), notify.build());
/*
Intent badgeIntent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
badgeIntent.putExtra("badge_count", 5);
badgeIntent.putExtra("badge_count_package_name", getPackageName());
badgeIntent.putExtra("badge_count_class_name", getLauncherClassName());
sendBroadcast(badgeIntent);
*/
Log.d(TAG, "update badge: " + getPackageName() + ", " + getLauncherClassName());
}
else {
Notification.Builder notify = new Notification.Builder(getApplicationContext());
notify.setSmallIcon(R.drawable.ic_stat_notification);
notify.setContentTitle(remoteMessage.getData().get("title"));
notify.setContentText(remoteMessage.getData().get("body"));
notify.setAutoCancel(true);
int id = NotificationID.getID();
Log.d(TAG, "id: " + id);
notiMgr.notify(id, notify.build());
}
}
else if ( remoteMessage.getNotification() != null ) {
Log.d(TAG, "onMessageReceived2: " + remoteMessage.getNotification().getTitle());
Log.d(TAG, "onMessageReceived2: " + remoteMessage.getNotification().getBody());
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ) {
Notification.Builder notify = new Notification.Builder(getApplicationContext(), CHANNEL_ID);
notify.setSmallIcon(R.drawable.ic_stat_notification);
notify.setContentTitle(remoteMessage.getNotification().getTitle());
notify.setContentText(remoteMessage.getNotification().getBody());
notify.setAutoCancel(true);
notiMgr.notify(NotificationID.getID(), notify.build());
}
else {
Notification.Builder notify = new Notification.Builder(getApplicationContext());
notify.setSmallIcon(R.drawable.ic_stat_notification);
notify.setContentTitle(remoteMessage.getNotification().getTitle());
notify.setContentText(remoteMessage.getNotification().getBody());
notify.setAutoCancel(true);
notiMgr.notify(NotificationID.getID(), notify.build());
}
}
}
#Nullable
private String getLauncherClassName () {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
PackageManager pm = getApplicationContext().getPackageManager();
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resolveInfos) {
String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
if ( pkgName.equalsIgnoreCase(getPackageName())) {
return resolveInfo.activityInfo.name;
}
}
return null;
}
}
You don't need two services now.....
Check this topic:
FirebaseInstanceIdService is deprecated now.
You dont need this.
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
Use it like this.
AndroidManifest.xml
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static int NOTIFICATION_ID = 1;
#Override
public void onNewToken(String s) {
super.onNewToken(s);
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Code to create the Notification
}
}
gradle build
implementation 'com.google.firebase:firebase-core:16.0.3'
implementation 'com.google.firebase:firebase-messaging:17.3.0'
i am new to android, here is how i am reciving and showing notification, but the thing is everytime i am sending notification from server the code comes to onMessageReceived but not not displaying any notification on Android Phone testing :
public class MyFirebaseMessagingService extends FirebaseMessagingService{
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("Message Notic", "========================>>>>> >>>>> >>>>> Some message came: " +remoteMessage.getData().get("message"));
showNotification(remoteMessage.getData().get("message"));
}
private void showNotification(String message) {
Intent i = new Intent(this,MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentTitle("FCM Test")
.setContentText(message)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0,builder.build());
}
}
Here i am not able to get the data on two devices i tested :
OnePlus 5 - Android Version (Oreo 8.0.0)
Le Echo - Android Version (6.0.0)
Any issue you can address here will be great! Why i am not seeing any notification.
Thank you!
Add this in your manifest.xml :
<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
MyFirebaseInstanceIDService.java
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
// TODO: Implement this method to send token to your app server.
}
}
MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
}
}
For Android O you must specify notification channel for your notification.
check the documentation
https://developer.android.com/guide/topics/ui/notifiers/notifications.html#ManageChannels
Hi Here i write it using Firebase Notification,i am used onMessageReceived to get notification,and send it on sendNotification functionality,Here my problem is ,my app is sleep mode,when i click the notification i need to go main activity page,but i got error ,its started from splash screen Here is my code on Firebase Messaging Service
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
String data;
String jsonObject;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom()); //MyFirebaseMsgService: From: 1055554437945
// Check if message contains a data payload.
data = String.valueOf(remoteMessage.getData());
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
if (remoteMessage.getData().size() > 0) {
jsonObject = remoteMessage.getData().toString();
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getTitle()); ////MyFirebaseMsgService: Message Notification Body: Customer request for service
if (remoteMessage.getNotification().getTitle().equalsIgnoreCase("Service Request")) {
sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getData().toString());
}
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
private void sendNotification(String messageBody, String values) {
Log.i("messageBodymageBody", "" + messageBody);
if (isUserLoggedIn()) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("values", values);
intent.putExtra("identify", "1");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(intent);
PendingIntent contentIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT
| PendingIntent.FLAG_ONE_SHOT);
startActivity(intent);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.fixmelogo)
.setContentTitle("Service Request")
.setContentText("Customer request for service")
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(contentIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
} else {
Intent intent1 = new Intent(this, LoginActivity.class);
startActivity(intent1);
}
}
public boolean isUserLoggedIn() {
Log.i("bollcheck", "" + UserInformations.getUserInformations(this).getId() + UserInformations.getUserInformations(this).getEmail());
/*if (UserInformations.getUserInformations(this).getId() != null || UserInformations.getUserInformations(this).getEmail() != null
|| UserInformations.getUserInformations(this).getMobile() != null) {*/
return UserInformations.getUserInformations(this).getId().trim().length() > 0;
}}
and also my manifest file
<application
android:name=".App"
android:allowBackup="true"
android:icon="#drawable/fixmelogo"
android:label="#string/app_name"
android:roundIcon="#drawable/fixmelogo"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Activity.SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".FirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".FirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/fixmelogo" />
<meta-data android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorPrimary" />
<activity android:name=".Activity.MainActivity"
android:exported="true"/>
<activity android:name=".Activity.TripActivity" />
</application>
when I click notification need to Main Activity, but it's going from splash Screen page, Sorry for my poor English, I am Beginner of the Android, kindly give some solution
Hi Here my Notification Json from Server
{
"to":"d7XvGt8pD60:APA91bEjEe9IjhjJDmojvRDogMp1xc4sQFT9EcoB8TBvM-rCtkwryFhRVGvHIx1T6CWMoJu3l4UuaXgkgWrFj_Fo1SFhip9C-RXuthO6pfHvJ4GRQOipWtiVjUl9wtO7jfVd-T6jMBpJ",
"notification":{
"body":"Customer request for service",
"title":"Service Request",
"sound":"mySound"
},
"data":{
"CustomerId":"99",
"CustomerName":"Mayil",
"CustomerLastName":"Kannan",
"PhoneNumber":"96788484887",
"PickupLocation":"Ponmeni Muniyaandi koil main road, Chandragandhi Nagar, Ponmeni, Madurai, Tamil Nadu 625016",
"DropLocation":"Ponmeni Muniyaandi koil main road, Chandragandhi Nagar, Ponmeni, Madurai, Tamil Nadu 625016",
"PickupLatitude":"9.92074762937605",
"PickupLongitude":"78.0926296301913",
"DropLatitude":"9.92074762937605",
"DropLongitude":"78.0926296301913"
}
}
they Are sending like this.
I have made an forum application in android and used phpmyadmin as my database. But when a question gets a new answer the application should show a notification to all users so how can i do it is there a need to use firebase or by just using a webservice!
Firstly, you need to go to the firebase console and create an app. (For this you will need to login into your google account) and follow the steps provided here.
https://firebase.google.com/docs/
Once that is done you will need to add these services to your Manifest.xml file
<service
android:name=".firebase.FirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service
android:name=".firebase.FirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
FirebaseInstanceIdService.class
public class FirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "FirebaseInstanceIDService";
#Override
public void onTokenRefresh() {
String token = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "OnTokenRefresh callback. Token received : " + token);
}
}
FirebaseMessagingService.class
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
private static final String TAG = "FirebaseMessagingService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG,"onMessageReceived.");
showNotification(remoteMessage.getData().get("message"));
}
private void showNotification(String message) {
Intent i = new Intent(this, HomeActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentTitle("Slapr Notification Demo")
.setContentText(message)
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0,builder.build());
}
}
Now you can get the tokenId in your activity by doing the following
Log.d(TAG, "Recieved token : " + FirebaseInstanceId.getInstance().getToken());
This are the most helpful tutorials that i had found when i started. I hope it helps you.
https://www.youtube.com/watch?v=LiKCEa5_Cs8
https://www.youtube.com/watch?v=MYZVhs6T_W8
I am writing an app that uses GCM Push Notifications, however when a notification appears, it opens the app but doesn't show the message. When I am in the app though, the messages show up normally. Please help.
This is my Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.amosang.pushtest" >
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- GCM Permissions - Start here -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission
android:name="com.example.amosang.pushtest.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.amosang.pushtest.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:exported="true"
android:name=".HomeActivity"
android:label="#string/title_activity_home" >
</activity>
<receiver
android:name=".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.REGISTRATION" />
<action android:name="com.example.amosang.pushtest" />
</intent-filter>
</receiver>
<service android:name=".GCMNotificationIntentService"
android:exported="false">
</service>
<activity
android:name=".NewRequest"
android:label="#string/title_activity_new_request" >
</activity>
</application>
Notification Code
public class GCMNotificationIntentService extends IntentService{
//set ID for the notification, so it can be updated
public static final int notifyID = 9001;
NotificationCompat.Builder builder;
public GCMNotificationIntentService() {
super("GcmIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
Log.d("GCMN","GCMNTEST");
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
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());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
.equals(messageType)) {
sendNotification("Message Received from Google GCM Server:\n\n"
+ extras.get(AppConstants.MSG_KEY));
}
}
GCMBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg){
Intent resultIntent = new Intent(this, HomeActivity.class);
Log.d("RECEIVEDPT2",msg);
resultIntent.putExtra("msg", msg);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this,0,resultIntent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mNotifyBuilder;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyBuilder = new NotificationCompat.Builder(this).setContentTitle("Alert")
.setContentTitle("You've received a new message")
.setSmallIcon(R.drawable.ic_cast_dark);
//Set pending intent
mNotifyBuilder.setContentIntent(resultPendingIntent);
//Set vibration
int defaults = 0;
defaults = defaults | Notification.DEFAULT_LIGHTS;
defaults = defaults | Notification.DEFAULT_VIBRATE;
defaults = defaults | Notification.DEFAULT_SOUND;
mNotifyBuilder.setDefaults(defaults);
// Set the content for Notification
mNotifyBuilder.setContentText("You have new notifications");
// Set autocancel
mNotifyBuilder.setAutoCancel(true);
// Post a notification
mNotificationManager.notify(notifyID, mNotifyBuilder.build());
}
As requested in the comments, please include the code for HomeActivity which handles the notification so we can examine the code and suggest solutions. In the meantime, this is how I'd suggest you process the incoming GCM notification in your HomeActivity class (will update the answer once I see you code, if necessary). In my example, I have a helper method processIntent(Intent intent) which handles the Intent and its Extras. I call this method from both onCreate and onNewIntent methods.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.<layout-id>);
//here I call our processing method
processIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//call our processing method
processIntent(getIntent());
}
/**
* Helper method to process the incoming GCM Notification.
* #param intent
*/
private void processIntent(Intent intent){
if(intent == null) { return; }
Bundle extras = intent.getExtras();
try{
if(extras.containsKey("msg")){
//possibly a message
String message = extras.getString("msg");
Log.i(TAG, "Received Message "+message);
//do whatever with the message, like set as Text of TextView, etc
}
}
catch(Exception e){
Log.e(TAG, "Error Processing GCM Notification Intent", e);
}
}