首页 > 解决方案 > 如何使用 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 令牌来定位特定用户并向他发送通知,但我找不到这样做的方法。请帮我。

标签: javaandroidpush-notificationfirebase-cloud-messaging

解决方案


要将通知发送给特定用户,您必须调用此 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();
}

推荐阅读