I am new to push notifications in android so i followed the following tutorial on android developer page.
http://developer.android.com/google/gcm/client.html
The thing i am not clear is in the intentservice class.It is shown below:
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.igloo.fragments.sportsfragment;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
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)) {
//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, sportsfragment.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
The thing that confuses me is the final method:
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());
Can someone please clarify why the pending intent is used here to DemoActivity.class.And also explain what this line does: mBuilder.setContentIntent(contentIntent);
My understanding is that it takes you to the class where you want to go when i click on the notifciation from the notification bar above.Is it right?
}
PendingIntent is set up as a "pointer" and stored by the system so that when the user selects the notification in the status bar the target activity specified in the notificationIntent can be called.
If you want to know something more http://examples.javacodegeeks.com/android/core/ui/notifications/android-notifications-example/
Related
Firebase offers two ways to seding a push notifications, using it's firebase console and using a server like in GCM was did before. Now we are translating our servers from GCM to Firebase, and we need to receive and show FCM notifications in the app.
I have the implementation of the official firebase website done, with the sample codes done, but I'm stuck on this part. When our server sends the push notification to Firebase, and firebase send's to my app, I'm receiving the notification in onMessageReceived method with a RemoteMessage parameter. I know that the message is inside RemoteMessage parameter, but I can't find any guide or sample code in the Firebase official documentation about how to deal with this to show the notification text on the android device notification bar.
As you can see on the official guides, it is not explained how to extract the message without problems from the RemoteMessage parameter. I know that you can search inside and find the String but I want to find a official guide about how to correctly and safely deal with this.
In the official documentation you have only this:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
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());
// Handle message within 10 seconds
}
// 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 this (which is not being called on the guide):
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 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_main)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
I have done something like this I am using addNotifcation() in place of sendNotification()
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getData().get("body"));
addNotification(remoteMessage.getData().get("body"), remoteMessage.getData().get("Nick"));
}
private void addNotification(String message, String title) {
NotificationCompat.Builder builder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher1)
.setContentTitle(title)
.setContentText(message);
Intent notificationIntent = new Intent(this, app.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
You will recieve a json onMessageRecieve from server then you need to parse that json and get values out of it.Once you have parsed value you can send it with sendNotification() Method and show what you require
Check below method, its working fine, I am getting json data from server in notification.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
AppLog.Log(TAG, "From: " + remoteMessage.getFrom());
JSONObject json = null;
if (remoteMessage.getData().size() > 0) {
Log.v(TAG, "Message data " + remoteMessage.getData());
json = new JSONObject(remoteMessage.getData());
AppLog.Log(TAG, "Json object " + json);
}
if (json != null) {
try {
int icon = R.mipmap.ic_launcher;
int mNotificationId = 001;
// MainDrawerActivity is the class which open on the click of notification in status bar
Intent intent = new Intent(this, MainDrawerActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//FLAG_UPDATE_CURRENT is important
PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this);
Notification notification = mBuilder.setSmallIcon(icon).setTicker("your title").setWhen(0)
.setAutoCancel(true)
.setContentTitle("your title")
.setStyle(new NotificationCompat.BigTextStyle().bigText("message"))
.setContentIntent(pendingIntent)
.setContentText("message").build();
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(mNotificationId, notification);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
I have followed this tutorial and when I try to send a message from Firebase console, onMessageReceived were called and createNotification were performed, no notification prompt shows up.
It suppose to prompt this but it didn't
Below is my MyAndroidFirebaseMsgService code
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import java.util.HashMap;
public class MyAndroidFirebaseMsgService extends FirebaseMessagingService
{
private static final String TAG = "MyAndroidFCMService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Log data to Log Cat
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
//create notification
createNotification(remoteMessage.getNotification().getBody());
}
private void createNotification( String messageBody)
{
Intent intent = new Intent( this , ResultActivity.class );
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent resultIntent = PendingIntent.getActivity( this , 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder( this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Test Notification")
.setContentText(messageBody)
.setAutoCancel( false )
.setSound(notificationSoundURI)
.setContentIntent(resultIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mNotificationBuilder.build());
}
}
Finally found that the notification were actually only appeared on the android drop down menu instead of popping up due to my device is running Android 4. I test again with Android 5 device and the notification pop up just like the tutorial.
Maybe you were missing notification notify.
Please try bellow code. it's working properly
//This method is only generating push notification
//It is same as we did in earlier posts
private void sendNotification(RemoteMessage remoteMessage) {
Intent resultIntent = new Intent(this, MenuBarActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
HashMap<String, String> dataMap = new HashMap<String, String>(remoteMessage.getData());
resultIntent.putExtra(Constant.KEY_MESSAGE_BODY, dataMap);
resultIntent.putExtra(Constant.KEY_IS_NOTIFICATION, true);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getData().get(Constant.KEY_BODY)))
.setContentText(remoteMessage.getData().get(Constant.KEY_BODY))
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setSound(defaultSoundUri);
// if (!BaseActivity.isInForeground()) {
notificationBuilder.setContentIntent(pendingIntent);
// }
// Generate ID
long time = new Date().getTime();
String tmpStr = String.valueOf(time);
String last4Str = tmpStr.substring(tmpStr.length() - 5);
int notificationId = Integer.valueOf(last4Str);
// Sets an ID for the notification
// int notificationId = Constant.NOTIFICATION_ID;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(notificationId, notificationBuilder.build());
}
This question already has answers here:
Firebase onMessageReceived not called when app in background
(30 answers)
Closed 6 years ago.
In Firebase onMessageReceived(RemoteMessage remoteMessage), this method will be called when your app is in Foreground. So, on clicking the notification you can open a different Activity, say NotiicationActivity.
But what if your app is in background, then this method will not be called, and on clicking the notification only a Launcher Activity will be opened.
So how to open the NotificationActivity on clicking the notification even if our app is in background.
My Code is this :
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
sendNotification(remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("key", messageBody);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Bitmap icon2 = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("FCM Sample")
.setContentText(messageBody)
.setAutoCancel(true)
.setLargeIcon(icon2)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(new Random().nextInt() /* ID of notification */, notificationBuilder.build());
}
}
onMessageReceived is only triggered when the application is in foreground.
If the app is backgrounded, you may still be able to receive the notification but onMessageReceived will not be triggered.
So my suggestion,
on the receiving activity, you can still get the data from the notification by using:
getIntent().getExtras();
This should work accordingly. Hope this helps :)
try and follow below link :
Firebase Cloud Messaging for Android
In your sendNotification() method :
private void showNotification(String message){
Intent intent=new Intent(this, NotificationActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("key", messageBody);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder=new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentTitle("FCM Sample")
.setContentText(message)
.setLargeIcon(icon2)
.setContentIntent(pendingIntent);
NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0,builder.build());
}
I am working on PUSH Notification.I am using the following code while receiving messages form GCM :
public class MyGcmListenerService extends GcmListenerService {
private static final String TAG = "MyGcmListenerService";
/**
* Called when message is received.
*
* #param from SenderID of the sender.
* #param data Data bundle containing message data as key/value pairs.
* For Set of keys use data.keySet().
*/
// [START receive_message]
#Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.e(TAG, "From: " + from);
Log.e(TAG, "Message: " + message);
if (from.startsWith("/topics/")) {
// message received from some topic.
} else {
// normal downstream message.
}
// [START_EXCLUDE]
/**
* Production applications would usually process the message here.
* Eg: - Syncing with server.
* - Store message in local database.
* - Update UI.
*/
/**
* In some cases it may be useful to show a notification indicating to the user
* that a message was received.
*/
sendNotification(message);
// [END_EXCLUDE]
}
// [END receive_message]
/**
* Create and show a simple notification containing the received GCM message.
*
* #param message GCM message received.
*/
private void sendNotification(String message) {
Intent intent = new Intent(this, WelcomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
//.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle("GCM Message")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notificationBuilder.build());
}
}
Message is received but is not displayed as notification.I don't know what i am missing here .Please help me to fix the issue .
Log:
03-07 16:50:21.617 32412-32678/com.almabay.almachat E/MyGcmListenerService﹕ From: 20130254292
03-07 16:50:21.618 32412-32678/com.almabay.almachat E/MyGcmListenerService﹕ Message: Hi Deepak this is is notification from GCM server. 07.03.2016 16:20:52
public void notify (int id, Notification notification)
Post a notification to be shown in the status bar. If a notification with the same id has already been posted by your application and has not yet been canceled, it will be replaced by the updated information.
http://developer.android.com/reference/android/app/NotificationManager.html#notify%28int,%20android.app.Notification%29
public void showNotificationMessage(String title, String message, Intent intent) {
if (TextUtils.isEmpty(message))
return;
int icon = R.drawable.ic_launcher;
int mNotificationId = new Random().nextInt(5000);
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext);
Notification notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setStyle(inboxStyle)
.setContentIntent(resultPendingIntent)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
// .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setContentText(message)
.build();
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(mNotificationId, notification);
}
Hope this will give idea to understand how notification works in android.
Hi im working on a project that uses push notifications to push out information in a text format. Only when i receive the push notification the text is cut off and replaced with "..."
Im using the NotificationCompaq builder to build my notifications when the app receives the information from the receiver.
Here is my GCMBroadcastReceiver Im pretty sure the issue is in the Builder but Im not sure what i need to do to fix it.
import utilities.CommonUtilities;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.gcm.GoogleCloudMessaging;
/**
* Handles the incoming messages from the server.
*
*/
public class GCMBroadcastReceiver extends BroadcastReceiver {
static final String TAG = "GCMDemo";
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
Context ctx;
#Override
public void onReceive(Context context, Intent intent) {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
ctx = context;
String messageType = gcm.getMessageType(intent);
String message = intent.getExtras().getString("price");
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(message);
}
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.icon)
.setContentTitle(CommonUtilities.pushTitle)
.setStyle(new NotificationCompat.BigTextStyle())
.setContentText(msg)
.setLights(0xff00ff00, 300, 1000)
.setVibrate(CommonUtilities.pattern);
Log.d(TAG, "Notification built " + mBuilder.toString());
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Toast.makeText(ctx, "New Message: " + msg, Toast.LENGTH_LONG).show();
}
}
Any help on this would be greatly appreciated thanks.
Edit
Ive checked the Message received from the GCM before my app builds the notification and i am receiving the full message there is nothing being cut off during the receiving of the message so it is definitely something to do with the Notification builder. I Just cannot seem to figure out whats causing it to do that.