Notification showing Wrongly in Firebase android - android

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.

Related

Handling fcm notification click

I am using fcm to send messages. The messages arrive to the app, but when the user clicks on the notification, t it supposed to open a link but it just opens the app. My manifest is like this
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id"/>
Where the notification is supposed to be handled :
Bundle extras = getIntent().getExtras();
if (extras != null && extras.containsKey("rateUpdate")) {
try {
startActivity(new Intent("android.intent.action.VIEW", Uri.parse("market://details?id=tino.varconn.com.fastnetworks")));
} catch (ActivityNotFoundException unused) {
startActivity(new Intent("android.intent.action.VIEW", Uri.parse("http://play.google.com/store/apps/details?id=tino.varconn.com.fastnetworks")));
}
}
When sending the message, I always make sure that in the key, value text boxes I put rateUpdate. Where am I going wrong here?
Inside FirebaseMessagingService class you can get content from push notification and build your own Notification
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Notification notification = remoteMessage.getNotification()
String title = notification.getTitle()
String body = notification.getBody();
//now you can build and show your own notification
}
with .setContentIntent() method, where you can set any Activity you want to start.
NotificationCompat.Builder builder = ...
Intent intent = new Intent(context, destinationClass);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent,
0);
builder.setContentIntent(contentIntent);

Android Firebase notification when application starts

I’m new to android.I programmed an app that uses Firebase to get push notifications. If I send a notification from the Firebase interface, the device receives the notification only when the app is running. Is there a way to get the notifications when the app is not running or at least to get all the unseen notifications when the app starts up?
Thank you in advance!
I add my code...
This is the class extending the FirebaseMessagingService:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public MyFirebaseMessagingService() {
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
sendNotification(remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageBody)
{
//Intent intent = new Intent (this, MainActivity.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher_round);
notificationBuilder.setContentTitle("My app");
notificationBuilder.setContentText(messageBody);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSound(defaultSoundUri);
//notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notificationBuilder.build());
}
}
and this is the class extending the FirebaseInstanceIdService:
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService{
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token)
{
}
}
Finally, this is the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="user.pushnotificationexample">
<uses-permission android:name="android.permission.INTERNET"/>
<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">
<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=".MyFirebaseInstanceIDService">
<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>
</manifest>
This is Xamarin Android solution, but it should get you close to native.
Try test sending a "data" push notification from an online tester like "pushwatch". Make sure to click the json checkbox and add a json payload that includes the key, "data":
{"data": {"title":"This is a title!","body":"This is the body text!"}}
The OnMessageReceived(RemoteMessage message) method, message parameter, has a dictionary property "Data": i.e. message.Data. You'll find the json payload key value pairs (title & body) in that dictionary.
Note, if the app is STOPPED, the user will OPEN the notification and Android will open the app, targeting the Activity used in the pending intent created and used to build the local notification (see below). You will need to handle the notification intent from the OnCreate method of your target Activity ( otherwise if the app is running, you'll handle the intent from an override of OnNewIntent).
public class MainActivity....
{
protected override void OnCreate(Bundle bundle)
{
...
var pushExtra = Intent.GetStringExtra("your.pushextra.key");
if(pushExtra != null)
{
MyType myType = JsonConvert.Deserialize<MyType>(pushExtra);
//if you have a framework like MVVM or startup process
//and your type
//is used for app navigation, you may need to store
//the string value in shared preferences and deserialize
//and use it later
//after the app has completely finished starting
}
}
}
Save yourself some effort, if you need a type or dictionary here, make sure to serialize the object when putting the extra (when you create the local notification) and then deserialize the pushExtra to your concrete type to use an instance of it above. You may find most examples put a string, or int or dictionary of key value pairs.
void ConfigureLocalNotification(MyType typeInstance)
{
...
var intent = new Intent(context, typeof(MainActivity));
var jsonData = JsonConvert.SerializeObject(typeInstance);
Log.Info(TAG, $"Adding IntentExtra: {jsonData}");
intent.PutExtra("your.pushextra.key", jsonData);
intent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop |
ActivityFlags.IncludeStoppedPackages); //| ActivityFlags.NewTask);
var pendingIntent = PendingIntent.GetActivity(context, 0, intent,
PendingIntentFlags.OneShot);
....
NotificationCompat.Builder builder = null;
builder = new NotificationCompat.Builder(context ...);
builder.SetContentIntent(pendingIntent) ....
}
Hope this helps

Configure click on the FCM push in the background

I'm having trouble starting a background activity using FCM click_action.
My manifesto:
<activity
android:name="com.myoro.MainActivity"
android:theme="#style/AppTheme.NoActionBar"/>
<activity
android:name="com.myoro.ActivityA"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="com.myoro.A" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.myoro.ActivityB"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="com.myoro.B" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
My message settings:
data: {{"type" : "A","id" : "a123","click_action": "com.myoro.A"}}
JAVA:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getData().size() > 0) {
if (remoteMessage.getData().containsKey("click_action")) {
Intent intent = new Intent(remoteMessage.getData().get("click_action"));
intent.putExtra("id", remoteMessage.getData().get("id"));
startActivity(intent);
return;
}
if (remoteMessage.getData().containsKey("data")) {
String data = remoteMessage.getData().get("data");
Gson gson = new Gson();
MyObj myObj = gson.fromJson(data, MyObj.class);
if(myObj.getType().equals("A")) {
Intent intent = new Intent(context, ActivityA.class);
intent.putExtra("id", myObj.getId());
startActivity(intent);
} else {
Intent intent = new Intent(context, ActivityB.class);
intent.putExtra("id", myObj.getId());
startActivity(intent);
}
}
}
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
In case I am trying to send this json model and it is always opening the activity main. How can I manipulate the notification click in fourground and background to open the ActivityA and ActivityB and need to pass the id?...
click_action is a parameter that should be used inside a notification message payload, not data.
Try to edit your payload to something like:
}
notification:{
"click_action": "com.myoro.A"
},
data: {
"type" : "A",
"id" : "a123"
}
}
See the FCM HTTP parameters for reference:
https://firebase.google.com/docs/cloud-messaging/http-server-ref

Android - Firebase notifications not working

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>

Android notifications not showing up in app

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);
}
}

Categories

Resources