I am using Firebase messaging to send notifications. What I want is if the user has logged in into the app only then she must get the notifications. But the notifications starts pouring the moment user downloads the app irrespective of whether the user has logged in into the app or not. How to handle this situation?
I didn't get anything helpful from the internet. Any help is appreciated.
MyFirebaseMessagingService.java
FirebaseUser firebaseUser;
private FirebaseAuth mAuth=FirebaseAuth.getInstance();
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String notificationTitle = null, notificationBody = null;
//shared preference to check if the user has logged in or not
SharedPreferences preferences=getSharedPreferences(LOGIN_PREF_NAME,MODE_PRIVATE);
String login_status=preferences.getString("accepted",null);
if (remoteMessage.getNotification() != null) {
Log.d(REGTAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
notificationTitle = remoteMessage.getNotification().getTitle();
notificationBody = remoteMessage.getNotification().getBody();
}
mAuthListener=new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null && !TextUtils.isEmpty(login_status) && login_status.equals("true")) {
PendingIntent pendingIntent=PendingIntent.getActivity(MyFirebaseMessagingService.this, INT, intent,
PendingIntent.FLAG_ONE_SHOT);
final NotificationCompat.Builder notificationBuilder;
notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setAutoCancel(true) //Automatically delete the notification
.setSmallIcon(R.mipmap.ic_launcher) //Notification icon
.setContentIntent(pendingIntent)
.setContentTitle(notificationTitle)
.setContentText(notificationBody);
mAuth = FirebaseAuth.getInstance();
firebaseUser=mAuth.getCurrentUser();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
if (firebaseUser != null ) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(INT, notificationBuilder.build());
}
}
};
mAuth.addAuthStateListener(mAuthListener);
}
}