java - 如何使用 FCM 令牌向 Android 中的特定用户发送通知?
问题描述
我在问如何使用 FCM 令牌向特定用户设备发送通知。令牌存储在 Firebase 中的 RealtimeDatabase 中,其结构如下:
project-name: {
users: {
username: {
name: "..."
token: "..."
}
}
}
这是我用来存储令牌的代码
FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (task.isSuccessful()) {
String token = task.getResult().getToken();
saveToken(token);
}
}
});
private void saveToken(String token) {
reference.setValue(token);
}
其中“参考”是指向数据库的正确指针。这可以正常工作。我想使用存储的令牌向目标用户发送推送通知。我还实现了 MyFirebaseMessagingService 类,但我不知道如何使用它使用我在上面发布的存储的 FCM 令牌向特定用户发送通知。
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
}
@Override
public void onNewToken(String token) {
Log.d(TAG, "Refreshed token: " + token);
sendRegistrationToServer(token);
}
private void sendRegistrationToServer(String token) {
//here I have code that store the token correctly
}
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);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_default)
.setContentTitle(getString(R.string.fcm_message))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, notificationBuilder.build());
}
}
所以我想通过他的 FCM 令牌来定位特定用户并向他发送通知,但我找不到这样做的方法。请帮我。
解决方案
要将通知发送给特定用户,您必须调用此 API:
https://fcm.googleapis.com/fcm/send
Authorization:"key=YOUR_FCM_KEY" 和 Content-Type:"application/json" 在标头中,请求正文应如下所示:
{
"to": "FCM Token",
"priority": "high",
"notification": {
"title": "Your Title",
"text": "Your Text"
},
"data": {
"customId": "02",
"badge": 1,
"sound": "",
"alert": "Alert"
}
}
您应该从后端调用此 api(推荐)。你也可以从你的安卓设备上调用它,但是
请注意劫持您的 API 密钥
对于 android 你可以使用okhttp来调用 API
implementation("com.squareup.okhttp3:okhttp:4.9.0")
示例代码就像
public static void senPushdNotification(final String body, final String title, final String fcmToken) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
OkHttpClient client = new OkHttpClient();
JSONObject json = new JSONObject();
JSONObject notificationJson = new JSONObject();
JSONObject dataJson = new JSONObject();
notificationJson.put("text", body);
notificationJson.put("title", title);
notificationJson.put("priority", "high");
dataJson.put("customId", "02");
dataJson.put("badge", 1);
dataJson.put("alert", "Alert");
json.put("notification", notificationJson);
json.put("data", dataJson);
json.put("to", fcmToken);
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json.toString());
Request request = new Request.Builder()
.header("Authorization", "key=YOUR_FCM_KEY")
.url("https://fcm.googleapis.com/fcm/send")
.post(body)
.build();
Response response = client.newCall(request).execute();
String finalResponse = response.body().string();
Log.i("TAG", finalResponse);
} catch (Exception e) {
Log.i("TAG", e.getMessage());
}
return null;
}
}.execute();
}
推荐阅读
- actions-on-google - 在 dialogflow 和 AoG 中同时运行代码,但由于 userStorage 而无法这样做
- excel - 通过 excel vba 脚本和 bexanalyzer 静默登录到 sap bw 服务器
- python - 在分组的 Pandas 数据框中删除最大值后的行
- riscv - 如何为 RISC-V Rocket-Chip 创建 SystemC 代码?
- vuejs2 - 如何聚焦和激活 vue 多选?
- ssl - '连接到 Podio API 失败:[35] 连接到 api.podio.com:443 时出现未知 SSL 协议错误
- java - java.io.IOException: error=12, 无法分配内存
- android - appcompat-v7:27.1.1 CardView 未在以前的 api 中显示
- intellij-idea - Linux Mint 19 Cinnamon 上的 IntelliJ IDEA Ultimate 渲染不良
- swift - 如何在 Vapor 3 中将字典转换为 JSON?