使用 FCM 向所有设备发送通知

问题描述 投票:0回答:0

我使用 firebase 实时数据库存储令牌,我可以将通知发送到我指定的一个设备 但是当我读取字符串列表中的所有标记并尝试通过发送字符串列表向所有标记发送通知时,它只是首先发送到一个设备 任何人有想法做

API

public interface API {
@FormUrlEncoded
@POST("send")
Call<ResponseBody> sendNotification(
        @Field("token") List <String> tokens,
        @Field("title") String title,
        @Field("body") String body
);

活动

 binding.btnSend.setOnClickListener(v -> {
        db.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for (DataSnapshot dataSnapshot: snapshot.getChildren()){
                    User_Model userModel = dataSnapshot.getValue(User_Model.class);
                    tokens.add(userModel.getToken());
                    // send notification to admin
                    API api = retrofit.create(API.class);
                    Call <ResponseBody> call = api.sendNotification(tokens,binding.etNotificationTitle.getText().toString(),binding.etNotificationBody.getText().toString());
                    call.enqueue(new Callback <ResponseBody>() {
                        @Override
                        public void onResponse(Call <ResponseBody> call, Response <ResponseBody> response) {

                        }

                        @Override
                        public void onFailure(Call <ResponseBody> call, Throwable t) {

                        }
                    });
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(AddNotificationActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    });

NotificationHelper

public class NotificationHelper {

public static void displayNotification(Context context,String title, String body){
    String id = "my_channel_id_01";
    Intent notificationIntent = new Intent(context, Cart_Fragment.class);
    notificationIntent.putExtra("cartId",2);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(context,
            0,notificationIntent,0);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context,id)
            .setContentTitle(title)
            .setContentText(body)
            .setSmallIcon(R.drawable.img_logo)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setVibrate(new long[]{100,1000,200,340})
            .setAutoCancel(false);
    builder.addAction(R.drawable.img_logo,"تاكيد الطلب",pendingIntent);
    builder.setColor(Color.BLUE);
    builder.setContentIntent(pendingIntent);

    NotificationManagerCompat managerCompat= NotificationManagerCompat.from(context);
    managerCompat.notify(1,builder.build());
}
}

MyFirebaseMessagingService

public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override
public void onMessageReceived(@NonNull RemoteMessage message) {
    super.onMessageReceived(message);

    if (message.getNotification() != null){
        String title = message.getNotification().getTitle();
        String body = message.getNotification().getBody();

        NotificationHelper.displayNotification(getApplicationContext(),title,body);
    }
}
}

index.js

const functions = require('firebase-functions');
var {google} = require('googleapis');
var MESSAGING_SCOPE = "https://www.googleapis.com/auth/firebase.messaging";
var SCOPES = [MESSAGING_SCOPE];

var express = require('express');
var app = express(); 

var bodyParser = require('body-parser');
var router = express.Router(); 

var request = require('request');


app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

router.post('/send', function(req, res){

getAccessToken().then(function(access_token){

    var title = req.body.title; 
    var body = req.body.body; 
    var token = req.body.token; 

    request.post({
        headers:{
            Authorization: 'Bearer '+access_token
        }, 
        url: "my url", 
        body: JSON.stringify(
            {
                "message":{
                    "token" : token,
                    "notification" : {
                        "body" : body,
                        "title" : title,
                    }
                }
            }
        )
    }, function(error, response, body){
        res.end(body);
        console.log(body);
    });
});
});

app.use('/api', router);


function getAccessToken(){
return new Promise(function(resolve, reject){
    var key = require("./service-account.json");
    var jwtClient = new google.auth.JWT(
        key.client_email,
        null,
        key.private_key,
        SCOPES,
        null
    );
    jwtClient.authorize(function(err, tokens){
        if(err){
            reject(err);
            return; 
        }
        resolve(tokens.access_token);
    });
});
}

exports.api = functions.https.onRequest(app);
javascript java android firebase retrofit
© www.soinside.com 2019 - 2024. All rights reserved.