这篇文章上次修改于 2229 天前,可能其部分内容已经发生变化,如有疑问可询问作者。 ### 用firebase向android和ios推送消息,ios 是apsalert,android 是androidNotification,首先添加依赖https://firebase.google.com/docs/admin/setup?hl=zh-cn ```xml com.google.firebase firebase-admin 6.4.0 ``` ### 初始化firebase app ```java @PostConstruct public void initFireBase() throws IOException { String path = this.getClass().getResource("/rr-hitube-firebase-adminsdk-ivopy-0743e9a8b3.json").getPath(); FileInputStream serviceAccount = new FileInputStream(path); FirebaseOptions options = new FirebaseOptions.Builder() .setCredentials(GoogleCredentials.fromStream(serviceAccount)) // .setDatabaseUrl("https://.firebaseio.com/") .build(); FirebaseApp.initializeApp(options); } ``` ### 发消息,注意对于一条消息,格式上要兼容ios和android ```java public void pushMessage(ConsumerRecord consumerRecord) { try { PushMessageEvent pushMessageEvent = JSON.parseObject(consumerRecord.value(), PushMessageEvent.class); String topic = ""; if (null != pushMessageEvent && null != pushMessageEvent.getUserId()) { topic = "9"; ApsAlert apsAlert = ApsAlert.builder() //ios格式 .setTitle(pushMessageEvent.getTitle()) .setBody(pushMessageEvent.getContent()) .setLaunchImage(pushMessageEvent.getImage()) .build(); AndroidNotification androidNotification = AndroidNotification.builder() //andorid格式 .setTitle(pushMessageEvent.getTitle()) .setBody(pushMessageEvent.getContent()) .setIcon(pushMessageEvent.getImage()) .build(); Message message = Message.builder() .setApnsConfig(ApnsConfig.builder() .putHeader("apns-priority", "10") .setAps(Aps.builder() .setAlert(apsAlert) .setBadge(1) .build()) .build()) .setAndroidConfig(AndroidConfig.builder().setNotification(androidNotification).build()) .putData("type",pushMessageEvent.getPushType().toString()) .setTopic(topic) .build(); String response = FirebaseMessaging.getInstance().send(message); System.out.println("Successfully sent message: " + response); } } catch (Exception e) { log.error("exception:", e); } } ``` 这样就收到标准的消息了
没有评论