Firebase Push Notifications does not receive - android

I'm trying firebase push notification. I did everything it said in the tutorial, but it isn't working.
FirebaseMessagingService:
package com.example.firebasenf.firebasenf;
import com.google.firebase.messaging.FirebaseMessagingService;/
public class MyFirebaseMessagingService extends FirebaseMessagingService {
}
FirebaseInstanceIdService:
package com.example.firebasenf.firebasenf;
import com.google.firebase.iid.FirebaseInstanceIdService;
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
}
Manifest:
<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>

you need to add some methods to your code :
FirebaseMessagingService:
package com.example.firebasenf.firebasenf;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage){
Intent intent = new Intent(this,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setContentTitle("Application Title");
notificationBuilder.setContentText(remoteMessage.getNotification().getBody());
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notificationBuilder.build());
}
}
FirebaseInstanceIdService :
package com.example.firebasenf.firebasenf;
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String REG_TOKEN = "REG_TOKEN";
#Override
public void onTokenRefresh(){
String recent_token = FirebaseInstanceId.getInstance().getToken();
Log.d(REG_TOKEN,recent_token);
}
}

you need to override onMessageReceived in MyFirebaseMessagingService class to do some actions when notification is pushed.
doc
By overriding the method FirebaseMessagingService.onMessageReceived,
you can perform actions based on the received RemoteMessage object and
get the message data
#Override
public void onMessageReceived(RemoteMessage remoteMessage)
{
Log.d(TAG, "From: " + "Notification Received");
// 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());
}
// 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.
//You may want show notification
}
keep in mind onMessageReceived will only triggered if the app in foreground
When your app is in the background, Android directs notification
messages to the system tray. A user tap on the notification opens the
app launcher by default.

Related

Android Not Showing Push Notification when using Firebase

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

Android app not receiving FCM push messages

I am trying to send push messages from Firebase to my Android application:
Both of the MyFirebaseInstanceIDService and MyFirebaseMessagingService class are inside the service package of my main package. Below is my folder structure
So in my AndroidManifest they are represented as
<service
android:name=".services.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<service
android:name=".services.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
MyFirebaseInstanceIDService class:
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();
#Override
public void onTokenRefresh() {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "-------- refreshedToken: " + refreshedToken);
//TODO: send the token to the node server to store it in mysql
}
}
MyFirebaseMessagingService class:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();
#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());
}
Intent intent = new Intent(this, SplashActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "280887");
notificationBuilder.setContentTitle("FCM Notification");
notificationBuilder.setContentText(remoteMessage.getNotification().getBody());
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher_round);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
The issue is when I run my app I do not get the registration token. All the examples I have seen online or youtube, they have all their files under single package. But in my case I got sub-packages for each type of file. Is this is issue?
Also, in MyFirebaseInstanceIDService when I store the token in shared preference and retrieve it in HomeActivity the token is null.
***************** EDIT*****************
My Logcat gives Tag Manager is not found and thus will not be used message. It is not showing any tags V, I, D non of them
You need to add your project in Firebase and then download a file named "google.json" and insert it inside your project. otherwise the authentication will fail and you won't receive any token.
Also you won't receive any new token until it changes.
on the other hand, Google usually doesn't send pushes immediately specially on Debug mode.
Send Registration To Server
Make sure you have added your project to Firebase and downloaded the correct google-services.json file and placed it in the Apps folder
Use the code similar to the one below and Register the token to the Server
package com.dev.gideon.services;
import [LOCATION-TO-YOUR-SHAREDPREF].SharedPref;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
public class FcmInstanceIDService extends FirebaseInstanceIdService {
private SharedPref sharedPref;
#Override
public void onTokenRefresh() {
sharedPref = new SharedPref(this);
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
sharedPref.setFcmRegId(token);
sharedPref.setOpenAppCounter(SharedPref.MAX_OPEN_COUNTER);
}
}
Try if it Helps!!!

intent to specific activity when push notification clicked in.

Not opening specific activity on notification click when the app is in background/not running
The notification-click starts specified activity only when the app is opened up and the notification-click is performed. If the app is in background/not running and the notification-click is performed, the application's MainActivity opens up. In short, it is like the app opens normally following the activity stack instead of opening the specified activity in the PendingIntent.
Firebase Instance Id Service:
package com.example.tamzid.pushnotification;
import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
public class MyAndroidFirebaseInstanceIdService extends
FirebaseInstanceIdService {
private static final String TAG = "MyAndroidFCMIIDService";
#Override
public void onTokenRefresh() {
//Get hold of the registration token
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
//Log the token
Log.d(TAG, "Refreshed token: " + refreshedToken);
}
private void sendRegistrationToServer(String token) {
//Implement this method if you want to store the token on your server
}
}
Firebase Message Service:
package com.example.tamzid.pushnotification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
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;
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("Android Tutorial Point FCM Tutorial")
.setContentText(messageBody)
.setAutoCancel( true )
.setSound(notificationSoundURI)
.setContentIntent(resultIntent);
NotificationManager notificationManager =
(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mNotificationBuilder.build());
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tamzid.pushnotification">
<application
android:name="android.support.multidex.MultiDexApplication"
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>
<activity android:name=".ResultActivity"></activity>
<service android:name=".MyAndroidFirebaseMsgService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".MyAndroidFirebaseInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"
/>
</intent-filter>
</service>
</application>
</manifest>
Try using remoteMessage.getData() instead of remoteMessage.getNotification()
Use remoteMessage.getNotification(): if message contains a
notification payload.
Use remoteMessage.getData():if message contains
a data payload.
Update onMessageReceived() as below:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0)
{
//create notification
createNotification(remoteMessage.getData().toString());
}
}

How to display a gcm push notification on the lock screen?

I want to send push notification to my android device and place them such that it is hard for the user to miss the push notification. Especially if the app is not running or is in background. I already know how to handle gcm push notification while the app is running. However, I am interested in how to customly display gcm message if the app is not running.
This is the situation I have right now:
App is closed/not running
I send a push notification with my python script and it is recieved on my device
A sound is played the screen keeps dark, no vibration
When hitting the sleep/wake button I can see a small notification
This is what I want:
App is closed/not running, device is locked, screen is off
I send a push notification via gcm to my device
when the message is recieved by my the device the following should happen
Phone should vibrate
Phone screen should turn on and show a custom notification
Phone should play a sound (okay, that already works)
After an extensive search on the net I have not found any resource yet that explains how to do that.
Can anybody provide a some guidance to me?
You can achieve that using WakefulBroadcastReceiver which prevents phone from sleeping and check GCM notification even if your app is not open.
Below are steps to achieve so
STEP-1 : You've to add WAKE_LOCK, INTERNET and other permissions in manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<permission android:name="your.package.name.permission.C2D_MESSAGE"
android:protectionLevel="signature"/>
<uses-permission android:name="your.package.name.permission.C2D_MESSAGE"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
STEP-2 : Register WakefulBroadcastReceiver and GCMMessageHandler also in manifest file under <application> tag
<receiver android:name=".gcm.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE"/>
<category android:name="com.hmkcode.android.gcm"/>
</intent-filter>
</receiver>
<service android:name=".gcm.GcmMessageHandler"/>
STEP-3 : Definition for GcmBroadcastReceiver is below
package your.package.name.gcm;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(),
GcmMessageHandler.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
STEP-4 : Definition of GcmMessageHandler is
package your.package.name.gcm;
import android.app.IntentService;
import android.app.Notification;
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;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import your.package.name.R;
import your.package.name.SplashScreen;
public class GcmMessageHandler extends IntentService {
public GcmMessageHandler() {
super("GcmMessageHandler");
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
protected void onHandleIntent(Intent intent) {
final Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if(!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
Log.e("GCM", "Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
Log.e("GCM", "Deleted messages on server: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
sendNotification(extras);
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(Bundle extras) {
try {
String message = extras.getString("message");
if(message != null) {
Log.e(tag, "Notification received " + message);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle("TITLE");
mBuilder.setContentText(message);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 1, new Intent(this, SplashScreen.class), PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setDefaults(Notification.DEFAULT_ALL); // this line sets the default vibration and sound for notification
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
} else {
Log.d(tag, "Message is empty.");
}
} catch (Exception ex) {
Log.e(tag, Log.getStackTraceString(ex));
}
}
}
Hope it'll help you.

Notifications from firebase when app is in foreground not called

I'm trying to setup a system where an Android mobile phone receives notification from a server: for this task we have chosen Firebase.
While the application is in background everything works fine: after I push a message from the firebase console a notification appears on the system tray and, after the message is clicked by the user, an Intent with extra data is sent to the Activity.
My problem is uniquely when the application is already in foreground. The firebase notification is pretty clear: if the application is in foreground, no matter which type of message is sent by the server, OnMessageReceived is never called... so why it fails with my simple app? Some notes to help you solve this issue:
we're working with Android Studio 2.1.2;
"it.bagozi.ada.tutorial.firebase" contains both classes (as you might deduce from the pacakge declaration);
Below you can find all the source code used:
Main Activity
package it.bagozi.ada.tutorial.firebase;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private TextView notification;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.notification = (TextView) this.findViewById(R.id.notification_setter);
Intent i = this.getIntent();
Log.e(TAG, "Intent from Activity caller: " + i);
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
Log.d(TAG, "Key: " + key + " Value: " + value);
}
}
}
}
FirebaseNotificationService
package it.bagozi.ada.tutorial.firebase;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
public class FirebaseNotificationService extends FirebaseMessagingService {
private static final String TAG = FirebaseNotificationService.class.getSimpleName();
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
Log.e(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.e(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.
}
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="it.bagozi.ada.tutorial.firebase">
<service android:name=".FirebaseNotificationService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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>
</application>
</manifest>
Make the service declaration in your manifest a child of the "application" tag!

Categories

Resources