I use FCM in Android, but I can't generate a token - android

I have use FCM in my Android application, but I can't fetch a token from FirebaseMessagingService.
I have this code:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.e(TAG, "From: " + remoteMessage.getFrom());
Log.e(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
//Calling method to generate notification
sendNotification(remoteMessage.getNotification().getBody());
}
but this class is not called. What do I do?

The FirebaseMessageService is the class responsible for communicating with FCM. Often with receiving the message payloads and is not responsible for generating the Registration Token.
In order to get the corresponding Registration Token, just call FirebaseInstanceId.getInstance().getToken() in your MainActivity's onCreate(). You should also monitor the event wherein a token changes in onTokenRefresh().
For more details, read through the Access the device registration token docs.

You can this method in any where in your String token = FirebaseInstanceId.getInstance().getToken();

Related

Firebase FCM not calling service when app is in background/killed

I am integrating firebase FCM push notifications on an android app and all things are working fine except when app goes background/killed, the MyFirebaseMessagingService is not called. It works fine when app is in foreground. The onMessageReceived() is not at all called when app is in background.
I want to send push notifications from Firebase console UI only to all subscribers at once, not trying to do 1-1 messaging or sending through web server.
Not that the service is not running when app is closed from Recent Apps tray, the app is not at all working when simply the app goes to background.
Below are the respective codes:
MyFirebaseMessagingService
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
// Not getting messages here? See why this may be:
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());
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
scheduleJob();
} else {
// Handle message within 10 seconds
handleNow();
}
}
// 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.
}
Service Declaration in Manifest
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Application Class Declaration
FirebaseMessaging.getInstance().subscribeToTopic("weather")
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
String msg = "Subscribed";
if (!task.isSuccessful()) {
msg = "Message";
}
Log.d("Token", msg);
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
});

How to make a heads up notification like the whatsapp notification with sound

I am new to android programming.I want my app to display a pop-up notification( its probably called a heads up notification) on the top of the screen whether it is in background or foreground and add sound to it but cant figure out how. The code is very basic.
MyFirebaseMessageService.java
public class MyFirebaseMessageService extends FirebaseMessagingService {
public static final String TAG = "FCM";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO: Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated.
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message: " + remoteMessage.getNotification().getBody());
}
}
MyFirebaseIdService.java
public class MyFirebaseIDService extends FirebaseInstanceIdService {
private static String TAG = "INSTANCEID";
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed Token: " + refreshedToken);
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
}
}
Do you want your notification to be on the screen, or on the notification bar?
For a simple on screen notification use a Toast.
Toast.makeText(getApplicationContext(),"Your message",Toast.LENGTH_SHORT).show();
For a notification bar notification take a look at NotificationBuilder.
You can make your notification make sound as well.

Retrieving Firebase Notifications at the start of the app

I know that, when the app is killed, it can't shows any Firebase notification... or this is what happens with my new app: I kill the app, The new notifications don't come up as well.
Now, I want to get rid of this problem in a new way: I want to retrieve, when my app starts, all the notifications the app "forgot" to see.
Here's my code
IdService
public class FirebaseIDService extends FirebaseInstanceIdService {
private static final String TAG = "FirebaseIDService";
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(refreshedToken);
}
/**
* Persist token to third-party servers.
*
* Modify this method to associate the user's FCM InstanceID token with any server-side account
* maintained by your application.
*
* #param token The new token.
*/
private void sendRegistrationToServer(String token) {
// Add custom implementation, as needed.
}
}
and the message class
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO: Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated.
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
notifies(remoteMessage.getNotification().getBody());
}
private void notifies(String body){
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(MyFirebaseMessagingService.this)
.setSmallIcon(android.R.drawable.ic_menu_help)
.setContentTitle("Congratulations!")
.setContentText(body);
Notification mNot= mBuilder.build();
// Display
NotificationManager mNotMan = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
mNotMan.notify(1,mNot);
}
}
What can you suggest to me? Thanks for all the answers :D
IMHO the best way to do this is create a notification center server side.
So , every time when you send a push notification save it on server.
When your app is starting up get push notifications list remotely.

running Firebase Cloud messaging onMessageReceived when sleep or in background without user action

I implemented Firebase cloud messaging in my app to execute code in the overridden onMessageReceived function. IT works fine when the app is in the foreground but not when idle/sleep or in background. I do receive the message in the notification tray but the code doesn't run. I know an action could be set up to run the code when a user clicks the notification in the trey but I want it to run without any user interaction. Is there a way to get this to run or is there a better solution that FCM.
The end goal is to ping the device from a server (done now through the FCM token) and then immediately have the device upload the devices location. Is there a better way?
Here is my FCM code.
import android.content.Intent;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import java.util.Map;
import static android.content.ContentValues.TAG;
public class FMS extends FirebaseMessagingService {
public FMS() {
}
public static final String INTENT_FILTER = "Remote_Execute";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Intent intent = new Intent(INTENT_FILTER);
sendBroadcast(intent);
Map<String, String> data = remoteMessage.getData();
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());
}
}
}
see the difference between data messages and notification messages in the firebase cloud messaging documentation
https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages

Firebase Cloud Messaging onMessageReceived not getting triggered

As instructed in Firebase dev docs, I've implemented a Service that extends FirebaseMessagingService and overrides the onMessageReceived callback. I have put a Log message in the first line inside the onMessageReceived method.
App running in background
I don't see the log in logcat but I see a Notification posted in the system try.
App in Foreground
I neither see the log nor the notification in system tray
Any idea what's going on?
Manifest
<service
android:name=".fcm.MovieMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
Service Class
public class MovieMessagingService extends FirebaseMessagingService {
private static final String LOG_TAG = MovieMessagingService.class.getSimpleName();
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(LOG_TAG, "From: " + remoteMessage.getFrom());
}
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
private void sendNotification(String messageBody) {
Log.d(LOG_TAG, "Presenting Notification with message body: " + messageBody);
//more code
}
}
Actually, app's behavior, while receiving messages including both notification and data payloads, depends on whether the app is in the background or the foreground like:
When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.
When in the foreground, your app receives a message object with both payloads attached.
So, The summary is when app is in background, you can see the notification in system tray and can't see any log until tapping on the notification but you will see only the opening activity log not the service log as it's already executed.
And when the app in foreground you can see the log in logcat but you can't see any notification in the system tray as your app already open state you will receive only data payloads.
Here is a code example of how to receive messages and how to handle the different types. Here is the source of the code.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// [START_EXCLUDE]
// There are two types of messages data messages and notification messages. Data messages are handled
// here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
// traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated notification is displayed.
// When the user taps on the notification they are returned to the app. Messages containing both notification
// and data payloads are treated as notification messages. The Firebase console always sends notification
// messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
// [END_EXCLUDE]
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());
}
}

Categories

Resources