使用Android应用将通知发送到FCM

时间:2019-03-14 11:52:54

标签: android firebase firebase-cloud-messaging

我要构建客户端和管理员android应用程序,以便管理员应用程序向FCM(API)发送通知,并且客户端应用程序的用户会收到此通知。

因此,我使用Firebase Admin SDK通过使用FCM documentation将通知从管理应用程序推送到FCM,但是下一个代码(来自文档)中有些奇怪的地方

// This registration token comes from the client FCM SDKs.
String registrationToken = "YOUR_REGISTRATION_TOKEN";

// See documentation on defining a message payload.
Message message = Message.builder()
.setNotification(new Notification(
    "$GOOG up 1.43% on the day",
    "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day."))
.setCondition(condition)
.build();


// Send a message to the device corresponding to the provided
    // registration token.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
 System.out.println("Successfully sent message: " + response);

由于send(RemoteMessage)接受RemoteMessage而不是Message对象,因此如何修改先前的代码以使用RemoteMessage对象发送通知

2 个答案:

答案 0 :(得分:1)

您似乎正在尝试将Firebase Admin SDK与适用于Android的Firebase Cloud Messaging SDK混合使用。这是不可能的。

任何使用Admin SDK的进程都将被授予对Firebase项目的完全,无限访问权限。因此,如果您将其放在客户端应用程序中,则使用该应用程序的每个人都可以将FCM消息发送给您的任何用户,而且还可以:列出所有这些用户,删除整个数据库,覆盖您的Cloud Functions等。 Firebase Admin SDK应该/只能在受信任的环境中使用的原因,例如您的开发计算机,您控制的服务器或Cloud Functions。

要通过Firebase Cloud Messaging将消息发送到到设备,您将始终需要具有受信任的环境,在FCM文档中通常将其称为 app服务器

在该受信任的环境上运行Admin SDK时,您可以调用FirebaseMessaging.getInstance().send() method,它将Message返回的build()作为其参数。

另请参阅:

答案 1 :(得分:0)

使用“我的代码”就像是超级按钮: 向特定用户发送通知并管理通知的点击。

implementation 'com.google.firebase:firebase-messaging:20.1.3'
implementation 'com.google.firebase:firebase-analytics:17.2.3'

清单

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="default_channel_id" />

    <service
        android:name=".FCMService" >
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

活动

  1.  project setting > cloud messaging > server key
      AUTH_KEY = server key

  2.  token id of a particular device is 
      String device_token = FirebaseInstanceId.getInstance().getToken();

发送通知时

  new Thread(new Runnable() {
        @Override
        public void run() {
            pushNotification(senderName + " : " + message);

        }
    }).start();

  private void pushNotification(String message) {
    JSONObject jPayload = new JSONObject();
    JSONObject jNotification = new JSONObject();
    JSONObject jData = new JSONObject();
        try {
            // notification can not put when app is in background
            jNotification.put("title", getString(R.string.app_name));
            jNotification.put("body", message);
            jNotification.put("sound", "default");
            jNotification.put("badge", "1");
            jNotification.put("icon", "ic_notification");

//            jData.put("picture", "https://miro.medium.com/max/1400/1*QyVPcBbT_jENl8TGblk52w.png");

            //to token of any deivce
            jPayload.put("to", device_token);

            // data can put when app is in background
            jData.put("goto_which", "chatactivity");
            jData.put("user_id", mCurrentUserId);

            jPayload.put("priority", "high");
            jPayload.put("notification", jNotification);
            jPayload.put("data", jData);

            URL url = new URL("https://fcm.googleapis.com/fcm/send");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization", "key=" + AUTH_KEY);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);

            // Send FCM message content.
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(jPayload.toString().getBytes());

            // Read FCM response.
            InputStream inputStream = conn.getInputStream();
            final String resp = convertStreamToString(inputStream);

        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }
    }

    private String convertStreamToString(InputStream is) {
        Scanner s = new Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next().replace(",", ",\n") : "";
    }

添加服务等级

    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    import android.media.RingtoneManager;
    import android.net.Uri;
    import android.util.Log;

    import androidx.annotation.NonNull;
    import androidx.core.app.NotificationCompat;

    import com.google.android.gms.tasks.OnCompleteListener;
    import com.google.android.gms.tasks.Task;
    import com.google.firebase.iid.FirebaseInstanceId;
    import com.google.firebase.iid.InstanceIdResult;
    import com.google.firebase.messaging.FirebaseMessagingService;
    import com.google.firebase.messaging.RemoteMessage;

    public class FCMService extends FirebaseMessagingService {
        String goto_which, user_id;

        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            super.onMessageReceived(remoteMessage);
            Log.d("ff", "messddda recice: " + remoteMessage.getNotification().getTicker());
            String title = remoteMessage.getNotification().getTitle();
            String body = remoteMessage.getNotification().getBody();

            if (remoteMessage.getData().size() > 0) {
                goto_which = remoteMessage.getData().get("goto_which").toString();
                user_id = remoteMessage.getData().get("user_id").toString();
                Log.d("ff", "messddda send: " + goto_which);
            }
            sendnotification(title, body, goto_which, user_id);
        }

        private void sendnotification(String title, String body, String goto_which, String user_id) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.putExtra("goto_which", goto_which);
            intent.putExtra("user_id", user_id);

            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
            Uri defaultsounduri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder nbuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_launcher_background)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setAutoCancel(true)
                    .setSound(defaultsounduri)
                    .setContentIntent(pendingIntent);

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, nbuilder.build());


            FirebaseInstanceId.getInstance().getInstanceId()
                    .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                        @Override
                        public void onComplete(@NonNull Task<InstanceIdResult> task) {
                            if (!task.isSuccessful()) {
                                Log.w("f", "getInstanceId failed", task.getException());
                                return;
                            }

                            // Get new Instance ID token
                            String token = task.getResult().getToken();

                        }
                    });

        }
    }

管理通知的点击:

它会调用启动器活动,因此在启动器活动中,您可以管理特定活动的调用

您的启动器活动看起来像

 if (getIntent().getExtras() != null) {
        String goto_which = getIntent().getStringExtra("goto_which");
        String chatUser = getIntent().getStringExtra("user_id");

        if (goto_which.equals("chatactivity")) {
            Intent chatIntent = new Intent(getBaseContext(), ChatActivity.class);
            chatIntent.putExtra("user_id", chatUser);
            startActivity(chatIntent);
        } else if (goto_which.equals("grpchatactivity")) {
            Intent chatIntent = new Intent(getBaseContext(), GroupChatActivity.class);
            chatIntent.putExtra("group_id", chatUser);
            startActivity(chatIntent);
        }
    }
相关问题