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.
Related
I have a small application where I receive the message from the Firabase cloud Messaging just fine while the app is running our while is on background. I search a lot about this and I could not find a proper answer on how to receive/create notifications in android while the app is closed so please do not think this is a duplicate question. Can someone show me an example about this and how its done?
This is my Firebase messaging service class
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static final String tag = "TAG";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(tag,"FROM"+remoteMessage.getFrom());
//check if message contains data
if(remoteMessage.getData().size()>0){
Log.d(tag,"Message Data" + remoteMessage.getData());
}
//check if message constains notification
if(remoteMessage.getNotification() != null){
sendNotification(remoteMessage.getNotification().getBody());
}
}
private void sendNotification(String body){
Intent i = new Intent(this,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Firebase CLoud Messaging")
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0,notificationBuilder.build());
}
}
This is my manifest
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
As per the docs, there are two types of notifications you can send through FCM.
Notification message
Data message
The firebase console can only send the first type of message. And the Notification message will be handled by the system if your app is in the backgroud, but it won't work if your app is stopped.
Switch to your own API, and send data messages.
So after hours with this problem and with the help of #Mauker I finally did it. These are the steps I took and all the information I received from the internet.
First of all forget Firebase Cloud Message to send notifications to your mobile app.
Second use postman to do those actions.
Notifications are of two types, group notifications where all the people receive the notification at the same time and direct notifications where the notification itself is only for the user to see.
1º If you want group notifications you have to do in you Application launcher class this:
FirebaseMessaging.getInstance().subscribeToTopic("groupNameChoosenByYou");
2º Then you have to create a class to handle this
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
String myCustomKey = data.get("title"); //received from postman POST as you can see above
Intent i = new Intent(this,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(myCustomKey)
.setContentText(myCustomKey+myCustomKey)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0,notificationBuilder.build());
}
}
3º Go to postman and do this in your body
This should be your URL : https://fcm.googleapis.com/fcm/send
{
"to":"/topics/groupNameChoosenByYou",
"data":
{
"title":"Your title",
"message":"Your message"
}
}
4º While in postman and do this in your Headers
Authorization -> Project settings in Firebase -> Cloud Messaging and take the Server key
Content-type -> application/json
5º If you want to do a direct notification for some specific user in the
"to":"/topics/groupNameChoosenByYou", replace with the device token id that is generated on the first connection with firebase(when the application is installed)
6º If you want to send notifications while the application is closed some ROMs dont allow this except facebook, whatsapp(golden apps) etc you must go to your battery optimization and put your app in the protected application(this changes from brand to brand). The ideal approach is to give the user an initial popup to help him do this.
This is what I learned and it works for me. Any question post above, I will try to research more about this and update while I get more information.
I’m new to android.I programmed an app that uses Firebase to get push notifications. If I send a notification from the Firebase interface, the device receives the notification only when the app is running. Is there a way to get the notifications when the app is not running or at least to get all the unseen notifications when the app starts up?
Thank you in advance!
I add my code...
This is the class extending the FirebaseMessagingService:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public MyFirebaseMessagingService() {
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
sendNotification(remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageBody)
{
//Intent intent = new Intent (this, MainActivity.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher_round);
notificationBuilder.setContentTitle("My app");
notificationBuilder.setContentText(messageBody);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSound(defaultSoundUri);
//notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notificationBuilder.build());
}
}
and this is the class extending the FirebaseInstanceIdService:
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService{
#Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token)
{
}
}
Finally, this is the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="user.pushnotificationexample">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name=".MyFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
</manifest>
This is Xamarin Android solution, but it should get you close to native.
Try test sending a "data" push notification from an online tester like "pushwatch". Make sure to click the json checkbox and add a json payload that includes the key, "data":
{"data": {"title":"This is a title!","body":"This is the body text!"}}
The OnMessageReceived(RemoteMessage message) method, message parameter, has a dictionary property "Data": i.e. message.Data. You'll find the json payload key value pairs (title & body) in that dictionary.
Note, if the app is STOPPED, the user will OPEN the notification and Android will open the app, targeting the Activity used in the pending intent created and used to build the local notification (see below). You will need to handle the notification intent from the OnCreate method of your target Activity ( otherwise if the app is running, you'll handle the intent from an override of OnNewIntent).
public class MainActivity....
{
protected override void OnCreate(Bundle bundle)
{
...
var pushExtra = Intent.GetStringExtra("your.pushextra.key");
if(pushExtra != null)
{
MyType myType = JsonConvert.Deserialize<MyType>(pushExtra);
//if you have a framework like MVVM or startup process
//and your type
//is used for app navigation, you may need to store
//the string value in shared preferences and deserialize
//and use it later
//after the app has completely finished starting
}
}
}
Save yourself some effort, if you need a type or dictionary here, make sure to serialize the object when putting the extra (when you create the local notification) and then deserialize the pushExtra to your concrete type to use an instance of it above. You may find most examples put a string, or int or dictionary of key value pairs.
void ConfigureLocalNotification(MyType typeInstance)
{
...
var intent = new Intent(context, typeof(MainActivity));
var jsonData = JsonConvert.SerializeObject(typeInstance);
Log.Info(TAG, $"Adding IntentExtra: {jsonData}");
intent.PutExtra("your.pushextra.key", jsonData);
intent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop |
ActivityFlags.IncludeStoppedPackages); //| ActivityFlags.NewTask);
var pendingIntent = PendingIntent.GetActivity(context, 0, intent,
PendingIntentFlags.OneShot);
....
NotificationCompat.Builder builder = null;
builder = new NotificationCompat.Builder(context ...);
builder.SetContentIntent(pendingIntent) ....
}
Hope this helps
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!!!
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.
I have made an forum application in android and used phpmyadmin as my database. But when a question gets a new answer the application should show a notification to all users so how can i do it is there a need to use firebase or by just using a webservice!
Firstly, you need to go to the firebase console and create an app. (For this you will need to login into your google account) and follow the steps provided here.
https://firebase.google.com/docs/
Once that is done you will need to add these services to your Manifest.xml file
<service
android:name=".firebase.FirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service
android:name=".firebase.FirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
FirebaseInstanceIdService.class
public class FirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "FirebaseInstanceIDService";
#Override
public void onTokenRefresh() {
String token = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "OnTokenRefresh callback. Token received : " + token);
}
}
FirebaseMessagingService.class
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
private static final String TAG = "FirebaseMessagingService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG,"onMessageReceived.");
showNotification(remoteMessage.getData().get("message"));
}
private void showNotification(String message) {
Intent i = new Intent(this, HomeActivity.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("Slapr Notification Demo")
.setContentText(message)
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0,builder.build());
}
}
Now you can get the tokenId in your activity by doing the following
Log.d(TAG, "Recieved token : " + FirebaseInstanceId.getInstance().getToken());
This are the most helpful tutorials that i had found when i started. I hope it helps you.
https://www.youtube.com/watch?v=LiKCEa5_Cs8
https://www.youtube.com/watch?v=MYZVhs6T_W8