2

I am creating a BloodBank app in which, when the user requests for the blood, It takes the requested Blood group and search the same in the database. It displays list of all the users who can donate to that blood group.

In the list, I have already implemented an option to message and call the user. Additionally, I want the App to send a notification to all users who have the same blood group.

For achieving this I have subscribed the user to a topic at successful login and sent him a notification but I have done this through the console.

What I want to achieve is, as a user requests the blood and while showing him the list of all users who can donate, App should also send a notification to all the users who have subscribed to that topic.

So is there any possible way I can programmatically send FCM to all the users subscribed to the same topic.

Here I'm subscribing user to a topic at successful Login:

   firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        progressDialog.dismiss();
                        topicSubscription();

                    } else {
                        progressDialog.dismiss();
                        String exception = task.getException().getMessage();
                        HelperClass.showSnakbarMsg(rootView, exception);
                    }
                }
            });
        }

        private void topicSubscription() {
            FirebaseMessaging.getInstance().subscribeToTopic("Blood")
                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            String msg = getString(R.string.msg_subscribed);
                            if (!task.isSuccessful()) {
                                msg = getString(R.string.msg_subscribe_failed);
                            } else {
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                finish();
                            }
                            Log.d("log", msg);
                            Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
                        }
                    });

This is my Firebase messaging class:

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.
     */

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {


        // TODO(developer): Handle FCM messages here.

        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());
        }

    }

I have read about it and many have said to hit an API for this to send FCM programmatically. But I am creating the whole app in firebase so my DataBase is also in firebase and as my database is in firebase I can't use API for one notification only like I have to manage some table in DB for that notification and for only one table I have to manage a separate DB. So is there any way that I can send FCM programmatically to all users who have subscribed to the same topic, on successful loading of the donor list which shows the user who can donate to the requested blood group. Thanks

sud007
  • 5,824
  • 4
  • 56
  • 63
Umair Iqbal
  • 1,959
  • 1
  • 19
  • 38

2 Answers2

1

You can directly send push notification directly from android, to all the devices subscribed to the topic, check out the following link how to send msgs directly from android, but in this example user is sending message one to one, to send fcm message to user subscribed to a topic, you need to change the message format as specified by fcm documentation

ked
  • 2,426
  • 21
  • 24
0

User App

private void latLngNotification() {
    Location loc1 = new Location("");
    loc1.setLatitude(Double.parseDouble(userLat));
    //loc1.setLongitude();
    Location loc2 = new Location("");
    loc2.setLatitude(Double.parseDouble(attendanceLat));
    //loc2.setLongitude();
    float distanceInMeters = loc1.distanceTo(loc2);
    if (distanceInMeters > 50) {
        //Toast.makeText(this, "distance: " + distanceInMeters, Toast.LENGTH_SHORT).show();
        sendNotification();
    } else {
        //Toast.makeText(this, "distance: " + distanceInMeters, Toast.LENGTH_SHORT).show();
        Toast.makeText(this, "You are in home...", Toast.LENGTH_SHORT).show();
    }
}

private void sendNotification() {
    String TOPIC = "/topics/admin_app"; //topic has to match what the receiver subscribed to
    JSONObject notification = new JSONObject();
    JSONObject notifcationBody = new JSONObject();
    String title = "Quarantine outside";
    String message = mobileno + " User is out of his area";
    try {
        notifcationBody.put("title", title);
        notifcationBody.put("message", message);
        notification.put("to", TOPIC);
        notification.put("priority", "high");
        notification.put("data", notifcationBody);
    } catch (JSONException e) {
        Log.e(TAG, "onCreate: " + e.getMessage());
    }
    Notification(notification);
}

private void Notification(JSONObject notification) {
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://fcm.googleapis.com/fcm/send", notification,
            response -> Log.i(TAG, "onResponse: " + response.toString()),
            error -> {
                Toast.makeText(GetLocationActivity.this, "Request error", Toast.LENGTH_LONG).show();
                Log.i(TAG, "onErrorResponse: Didn't work");
            }) {
        @Override
        public Map<String, String> getHeaders() {
            Map<String, String> params = new HashMap<>();
            params.put("Authorization", "key=AAAAwxBqu5A:APA91bERpf-1rh02jLciILt1rsLv7HRrFVulMTEAJXJ5l_JGrSHf96qXvLQV0bIROob9e3xLK4VN8tWo-zBPUL39HjxyW4MsX5nKW_NiQlZGgLDCySVwHXADlg16mpLUjgASj--bk-_W");
            params.put("Content-Type", "application/json");
            return params;
        }
    };
    MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
}

Admin App

FirebaseMessaging.getInstance().subscribeToTopic("admin_app");

Intent intent = getIntent();
    if (intent != null) {
        String userPhone = intent.getStringExtra("message");
        //Toast.makeText(this, userPhone, Toast.LENGTH_SHORT).show();
        message_txt.setVisibility(View.VISIBLE);
        message_txt.setText(userPhone);
    } else {
        message_txt.setVisibility(View.GONE);
        //Toast.makeText(this, "no data", Toast.LENGTH_SHORT).show();
    }
Aftab Alam
  • 1,969
  • 17
  • 17