FCM demo cannot get token - android

I created a project on Firebase console. I had register the package on the Firebase console, But I can`t get any token from the log even hit the LOG TOKEN button in the app.
Then I try to send message with Firebase console and set to target to my app package name.I didn't get any incoming message from the log.
Code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private final String TAG = "HelloJni";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
// Example of a call to a native method
TextView tv = (TextView) findViewById(R.id.sample_text);
tv.setText(stringFromJNI());
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
Object value = getIntent().getExtras().get(key);
Log.d(TAG, "Key: " + key + " Value: " + value);
}
}
// [END handle_data_extras]
Button subscribeButton = (Button) findViewById(R.id.subscribeButton);
subscribeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// [START subscribe_topics]
FirebaseMessaging.getInstance().subscribeToTopic("news");
// [END subscribe_topics]
// Log and toast
String msg = getString(R.string.msg_subscribed);
Log.d(TAG, msg + ", " + FirebaseInstanceId.getInstance().getToken());
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
}
RegistrationIntentService.java
public class RegistrationIntentService extends IntentService {
private static final String TAG = "RegIntentService";
public RegistrationIntentService() {
super(TAG);
}
#Override
protected void onHandleIntent(Intent intent) {
String token = FirebaseInstanceId.getInstance().getToken();
Log.i(TAG, "FCM Registration Token: " + token);
}
}
MyFirebaseInstanceIDService.java
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
#Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "oncreate.........");
}
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is called when the InstanceID token
* is initially generated so this is where you would retrieve the token.
*/
// [START refresh_token]
#Override
public void onTokenRefresh() {
Log.e(TAG, "onTokenRefresh call...");
// Get updated InstanceID token.
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// 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);
}
// [END refresh_token]
/**
* 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) {
Log.d(TAG, " sendRegistrationToServer Refreshed token: " + 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 onCreate() {
super.onCreate();
Log.e(TAG, "oncreate..........");
}
/**
* 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]
// 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.
}
// [END receive_message]
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
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)
.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());
}
}
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name="com.example.hellojni.MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<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>
<service android:name="RegistrationIntentService" ></service>
</application>
OnCreate() for MyFirebaseInstanceIDService and MyFirebaseMessagingService was not called, and the token returns null.
The log:
02-20 18:05:28.273 23322-23322 W/InstanceID/Rpc: Failed to resolve REGISTER intent, falling back
02-20 18:05:28.273 23322-23322 W/InstanceID/Rpc: Both Google Play Services and legacy GSF package are missing
02-20 18:05:28.273 23322-23322 W/InstanceID/Rpc: Failed to resolve REGISTER intent, falling back
02-20 18:05:28.273 23322-23322 W/InstanceID/Rpc: Both Google Play Services and legacy GSF package are missing
02-20 18:05:28.273 23322-23322 D/HelloJni: Subscribed to news topic, null

The device or emulator you are testing on does not have Google Play Services or the Google Service Framework (GSF) installed. Most of the Firebase APIs use the capabilities of Google Play Services and will not run if it is not present on the device.

put this at last after dependency in your app level gradle.apply plugin: 'com.google.gms.google-services'
and put this into your project level gradle.classpath 'com.google.gms:google-services:3.0.0'
make sure you have puted google-service.json in app module.

you have to add .
apply plugin: 'com.google.gms.google-services'
in last line in your gradle file and .
classpath 'com.google.gms:google-services:3.0.0'
in your project level file . IntentService service class will called only ones when your app intralled so delete app every time and and intrall every time when you want to generate tocken

I see the reason. I run the app with Android phone made in China, and these phones has no google play service and store.

Related

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!!!

Fetch old notification from fcm Android

I am using FCM for notification and it is working good in all scenarios in Foreground and background. My problem is when I am logout from my application and another user send me message, I am not getting any notification as I am logout which is fine, but when I again login in my application I want to receive that old unread notification so how to do this any help would be appreciated following is the code I used
public class FirebaseIDService extends FirebaseInstanceIdService {
private static final String TAG = "FirebaseIDService";
Context ctx = this;
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
try {
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
Log.e("remote", remoteMessage.getData().get("type") + "");
Log.e("remoteMessage", remoteMessage.getData() + "");
Log.e("remoteMessagebody", remoteMessage.getData().get("body") + "");
// handling other data also according to my app which i am not mentioning
}
}
I have used this code for fetching old notification but didnot worked
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
and in manifest
<service
android:name=".MyFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".FirebaseIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
and in gradle
compile 'com.google.firebase:firebase-messaging:9.2.1'
An FCM message has its own lifetime -- 4 weeks default, could be modified by setting time_to_live in your payload. After that time, the message would be discarded.
What you could do is implement that each notif is saved in a your Server DB, if it is not read yet and you detect that the user re-logs in, re-send them as push notifications, or simply retrieve them in your app and display them as notifications.

How to ensure that the Firebase Messaging sample implementation is notified even if app process is dead?

When I build and run the Firebase Messaging Sample app (after obtaining and installing a custom google-services.json file from my Firebase Console, as described by the wizard within Android Studio), I can send a simple non-notification message to it with my test script, and it works.
... but only if the app has been started on the device.
If I fail to first start the app, or force-stop the app (from Settings | Apps) after it's been started, the message doesn't quite seem to get through. (I say that because I no longer see any logging output from my onMessageReceived method).
Some have reported that when a message is sent out, their app wakes up even if their app has not first been started -- which is great! Exactly what I want!
But I haven't been able to figure out what they're doing to make that happen.
What am I missing? How should I change this code to make sure that it receives the message even when the app has not been started, or after the app has been forcibly stopped?
Note: the code I'm running (below) is based very closely upon the Firebase Quickstarts for Android code which can be downloaded and built from within Android Studio (File | New | Import Sample ... and then find "Firebase Quickstarts for Android" within the list it populates). (I believe that Google hosts that same code on GitHub here: github.com/firebase/quickstart-android/tree/master/messaging‌​). I modified the logging output and comments slightly.
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.firebase.quickstart.fcm">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<!-- [START fcm_default_icon] -->
<!-- Set custom default icon. This is used when no icon is set for incoming notification messages. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_stat_ic_notification" />
<!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
notification message. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
<!-- [END fcm_default_icon] -->
<activity
android:name="com.google.firebase.quickstart.fcm.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>
<!-- [START firebase_service] -->
<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<!-- [END firebase_service] -->
<!-- [START firebase_iid_service] -->
<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<!-- [END firebase_iid_service] -->
<service android:name=".MyJobService"
android:exported="false">
<intent-filter>
<action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/>
</intent-filter>
</service>
</application>
MyFirebaseInstanceIDService.java
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is called when the InstanceID token
* is initially generated so this is where you would retrieve the token.
*/
// [START refresh_token]
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// 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);
}
// [END refresh_token]
/**
* 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) {
// TODO: Implement this method to send token to your app server.
}
}
MyFirebaseMessagingService.java
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]
// TODO(developer): Handle FCM messages here.
Log.d(TAG, "onMessageReceived: From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "onMessageReceived: 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, "onMessageReceived: 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.
}
// [END receive_message]
/**
* Schedule a job using FirebaseJobDispatcher.
*/
private void scheduleJob() {
// [START dispatch_job]
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("my-job-tag")
.build();
dispatcher.schedule(myJob);
// [END dispatch_job]
}
/**
* Handle time allotted to BroadcastReceivers.
*/
private void handleNow() {
Log.d(TAG, "Short lived task is done.");
}
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
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_stat_ic_notification)
.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());
}
}
bash test script
curl -X POST \
--Header "Authorization: key=<server key from Firebase Console>“ \
--Header "Content-Type: application/json" \
https://fcm.googleapis.com/fcm/send \
-d " \
{ \
\"to\”:\”<token returned by FirebaseInstanceId.getInstance().getToken()>\”, \
\"priority\": \"high\" \
}"
echo
The behavior you are observing is the result of the app being in the "Stopped State". This behavior was introduced in Android 3.1 and is described here in the section Launch controls on stopped applications:
Applications are in a stopped state when they are first installed but
are not yet launched and when they are manually stopped by the user
(in Manage Applications)
When an app is in Stopped state, the system will not deliver Broadcast intents to it, which means it will not receive Firebase messages. As far as I know, you can't get around this; the user must start the app for the first time. This tells the system that the user wants the app to be operational and it is safe to deliver Broadcast intents to it.
Here are some SO questions/answers related to Stopped State.

GCM Push Notification not received

I try this code for GCM push notification.
In this for send notification I use this. But it shows the message like Cool! Message sent successfully check your device... But My device does not receive Notification.
Try Firebase, here is the documentation of Push-Notification https://firebase.google.com/docs/cloud-messaging/ or you can check this tutorial https://www.simplifiedcoding.net/android-push-notification-tutorial-using-firebase/
You should use FCM. See
1) Add this line to build.gradle: dependencies {
compile 'com.google.firebase:firebase-messaging:9.8.0'}
2) Add this service to manifest.
<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
3) Add this class to your project. I suggest to you to save your FCM Token:
public class MyInstanceIDListenerService extends FirebaseInstanceIdService {
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d("FirebaseService", "Refreshed token: " + refreshedToken);
SharedPreferences sharedPref = getSharedPreferences("YOUR_SETTING_NAME", Context.MODE_PRIVATE);
//There are optional steps
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("token", refreshedToken);
//notify the token update
editor.putBoolean("tokenUpdate",true);
editor.commit();
//You can send this token to your server (if you have)
sendServer(refreshedToken)
}
}
4) Now register your app to https://console.firebase.google.com/. This will generate a JSON file that's you must put inside app folders.
5) For generate FCM message you have 2 possibility:
5.1) Use the default Firebase Console: https://console.firebase.google.com/project/fantamanager-2017/notification/compose
5.2) Built your server app (If you want, i can send to you my Php Server Code)
6) Add this Service to your Manifest.xml
<service android:name="FcmBroadcastReceiver">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
And create a class that can intercept the push:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final ID_NOTIFICATION = ...
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String from,data;
from=remoteMessage.getFrom());
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
data=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.
sendNotification(data);
}
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_stat_ic_notification)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(ID_NOTIFICATION, notificationBuilder.build());
}
}
Or, if you have a custom service, change the body of onMessageReceived function with this:
Map data = message.getData();
if (data.containsKey(YOUR_DATA_FIELD_1)) {
String field1= data.get(YOUR_DATA_FIELD_1).toString();
String field2= data.get(YOUR_DATA_FIELD_2).toString();
....
sendNotification(field1,field2...);
return;
}
Did you try a part or whole code ? Coz last I saw , new applications for gcm are closed. Only FCM is available. So you need to register as they say , implement the json file in app and proceed. If you already had a project which implemented gcm and you tried part of this code , then please check if the key is proper and you have not copied they key from this project or something . or maybe some meta data from manifest file is missing.

Not getting notification using Firebase in Eclipse

I've got Firebase building without any warnings using Eclipse (see related: Unable to find obfuscated Firebase class in Eclipse)
I try to send a test notification, however I'm not getting anything. I'm using a library project as well. This is my code:
AndroidManifest.xml
<application />
...
<!-- ==================================
FIREBASE
=================================== -->
<service
android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service
android:name=".MyFirebaseInstanceIdService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
....
</application>
These files are practically straight from the samples:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static final String PUSH_NOTIFICATION_TEXT = "pushnotificationtext";
private static final String TAG = "Firebase";
public static final int NOTIFICATION_ID = 1;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Handle data payload of FCM messages.
String messageId = remoteMessage.getMessageId();
RemoteMessage.Notification notification = remoteMessage.getNotification();
Map<String, String> data = remoteMessage.getData();
Log.d(TAG, "FCM Message Id: " + messageId);
Log.d(TAG, "FCM Notification Message: " + notification);
Log.d(TAG, "FCM Data Message: " + data);
sendNotification(this, notification.toString());
}
// Put the GCM message into a notification and post it.
private void sendNotification(Context context, String message) {
NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
final Intent intent = new Intent(context, Splash.class);
//intent.putExtras(bundle);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//Save push notification message to show when app starts
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putString(PUSH_NOTIFICATION_TEXT, message).commit();
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setAutoCancel(true)
.setVibrate(new long[] { 0, 500, 200, 500, 200, 500 })
.setContentIntent(contentIntent)
.setContentTitle(context.getString(R.string.app_name))
.setSmallIcon(R.drawable.ic_launcher)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setContentText(message)
.setWhen(System.currentTimeMillis()).setOngoing(false);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
Other class:
public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {
private static final String TAG = "Firebase";
private static final String FRIENDLY_ENGAGE_TOPIC = "friendly_engage";
/**
* The Application's current Instance ID token is no longer valid
* and thus a new one must be requested.
*/
#Override
public void onTokenRefresh() {
// If you need to handle the generation of a token, initially or
// after a refresh this is where you should do that.
String token = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "FCM Token: " + token);
// Once a token is generated, we subscribe to topic.
FirebaseMessaging.getInstance().subscribeToTopic(FRIENDLY_ENGAGE_TOPIC);
}
}
I send a message via the Firebase console targeting the package name with no luck. I'm uncertain what I should do to get this to work. Do I need to use the google-services.json file in some way?
Thanks
I don't use Eclipse and am not able to verify that these steps work. I hope they will get you started on the right path.
The Firebase framework is initialized by FirebaseInitProvider. You don't need to implement or subclass it. Just declare it in your manifest.
<provider
android:authorities="${applicationId}.firebaseinitprovider"
android:name="com.google.firebase.provider.FirebaseInitProvider"
android:exported="false"
android:initOrder="100" />
FirebaseInitProvider expects to find string resources that contain the configuration values for the project. In an app built with Android Studio and the Google Services Gradle Plugin, the resource values are created from the google-services.json file. Because you are not using AS and the plugin, you will need to define these resources in your res folder. The values can be found in your Project Settings at the Firebase Console or in the google-service.json file. Because you are only interested in messaging, some values may not be needed. To be safe, define them all initially.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="default_web_client_id" translatable="false">8888888888888-ooqodhln4cjj4qst7b4sadfiousdf7.apps.googleusercontent.com</string>
<string name="firebase_database_url" translatable="false">https://project-888888888888888.firebaseio.com</string>
<string name="gcm_defaultSenderId" translatable="false">888888888888</string>
<string name="google_api_key" translatable="false">AIzaSyB0Bhr1sfsydfsdfnwelhkOYifak_Go2xU</string>
<string name="google_app_id" translatable="false">1:888888888888:android:526f9740dfg987sdfg</string>
<string name="google_crash_reporting_api_key" translatable="false">AIzaSyDkG-g8hH7T4TV7Rrsdfgiopudfmn234897</string>
<string name="google_storage_bucket" translatable="false">project-8888888888888888888888.appspot.com</string>
</resources>
You can confirm that the initialization succeeded by putting this code in the onCreate() method of your main activity:
FirebaseOptions opts = FirebaseApp.getInstance().getOptions();
Log.i(TAG, "onStart: ID=" + opts.getApplicationId());
Log.i(TAG, "onStart: SenderId=" + opts.getGcmSenderId());
Log.i(TAG, "onStart: Key=" + opts.getApiKey());
If valid results are logged, it indicates the default FirebaseApp has been initialized, and you should be able to receive messages.

Categories

Resources