Android app not receiving FCM push messages - android

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

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

FCM demo cannot get token

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.

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.

Display Notification on Android Device using Firebase or any other way

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

Categories

Resources