以编程方式将 FCM 发送给订阅主题的用户



我正在创建一个血库应用程序,当用户请求血液时,它会获取请求的血型并在数据库中搜索相同的血型。它显示可以捐献给该血型的所有用户的列表。

在列表中,我已经实现了一个消息和呼叫用户的选项。此外,我希望该应用程序向具有相同血型的所有用户发送通知。

为此,我已经在成功登录时为用户订阅了一个主题,并向他发送了通知,但我已通过控制台完成了此操作。

我想要实现的是,当用户请求血液并向他显示所有可以献血的用户列表时,App 还应该向订阅该主题的所有用户发送通知。

那么,我可以通过编程方式将 FCM 发送给订阅同一主题的所有用户。

在这里,我在成功登录时为用户订阅了一个主题:

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

这是我的Firebase消息传递类:

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

我已经读过它,许多人说要为此点击一个 API 以编程方式发送 FCM。但是我正在 firebase 中创建整个应用程序,所以我的数据库也在 firebase 中,并且由于我的数据库在 firebase 中,我不能只将 API 用于一个通知,就像我必须在数据库中管理该通知的某个表,并且只有一个表我必须管理一个单独的数据库。 那么,在成功加载捐赠者列表时,我有什么方法可以以编程方式将 FCM 发送给订阅同一主题的所有用户,该列表显示了可以向请求的血型捐赠的用户。 谢谢

您可以直接从 android 向所有订阅该主题的设备发送推送通知,请查看以下链接如何直接从 android 发送消息,但在此示例中用户是一对一发送消息,要将 FCM 消息发送给订阅主题的用户,您需要更改 FCM 文档指定的消息格式

用户应用

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

管理员应用

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

相关内容

  • 没有找到相关文章

最新更新