简体   繁体   中英

Sending push notifications to multiple devices using FCM, SQL, java

I have a work service which sending push notifications to the registration device and it works well, but I have a problem sending push notifications to multiple devices. I'm trying to use loops but it doesn't help. I think that to count the responses maybe give me results. Maybe the problem in the boolean expression, I don't guess. Maybe somebody knows what to do in this situation. Thanks for response and code below:

 @RequestMapping(value = "/sendtodeviceid", method = RequestMethod.GET, produces = "application/json")
    public ResponseEntity<String> send() throws JSONException, SQLException {
        try {
            System.out.println("\n" + "send massege to devicesid" + "\n" + "start to get ID" + "\n");

            ArrayList <String> deviceList = new ArrayList<>();
            Statement statement = jdbcService.getStatement();
            String selSql = String.format("SELECT deviceid FROM courier WHERE isActive = true");
            ResultSet rs = statement.executeQuery(selSql);
            //   check equals for more deviceid
            while (rs.next()) {
                String deviceid = rs.getString("deviceid");
                System.out.println("DEVAICE ID which true from sending message " + "\n" + deviceid + "\n");
                deviceList.add(deviceid);
                if (!deviceid.equals(deviceid)) {
                    String newdeviceid = deviceid;
                    deviceList.add(newdeviceid);
                }
            }
            System.out.println(deviceList + "\n");
//          find some solution for loop sending message to all device
            for (String iddevice: deviceList) {
                System.out.println("DEVICE ID: " + iddevice + "\n");
//          create jsonObject look like this
//           {
//              "data":
//                     {"address":"latitude420&longitude420",
//                      "click_action":".MessageOrder",
//                      "order":"#420"},
//              "to":
//                    "d2Hxxa6PNYw",
//                    "priority":"high"
//             },{}
                do {    
                    JSONObject body = new JSONObject();
                    body.put("to", iddevice);
                    body.put("priority", "high");

//                JSONObject notification = new JSONObject();
//                notification.put("title", "Wise delivery");
//                notification.put("body", "It is personal order!!!");
//                notification.put("icon", "main_logo_black");
//                notification.put("click_action", ".MessageOrder");

                    JSONObject data = new JSONObject();
                    data.put("order", "#421");
                    data.put("address", "latitude420&longitude421");
                    data.put("click_action", ".MessageOrder");
//              data.put("icon","main_logo_black");

//              body.put("notification", notification);
                    body.put("data", data);

                    HttpEntity<String> request = new HttpEntity<>(body.toString());
                    System.out.println("JSON file request" + request);

                    CompletableFuture<String> pushNotification = androidPushNotificationsService.send(request);
                    CompletableFuture.allOf(pushNotification).join();

                    try {
                        String firebaseResponse = pushNotification.get();

                        return new ResponseEntity<>(firebaseResponse, HttpStatus.OK);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                } while (iddevice == null);

            }

        } catch (SQLException e) {
            System.out.println("don't selectSQL" + "\n" + "SELECT deviceid FROM courier ");
        }
        return new ResponseEntity<>("Push Notification ERROR!", HttpStatus.BAD_REQUEST);
    }

And terminal shows this:

// start
send message to devicesid
start to get ID
// get device id from database
DEVAICE ID which true from sending message
d2Hxxa6PNYw:
DEVAICE ID which true from sending message
eb0s9KRXac8:
// create the ArrayList
[d2Hxxa6PNYw, eb0s9KRXac8]
// and at this step I have a problem
DEVICE ID: d2Hxxa6PNYw

JSON file request<{"data":{"address":"latitude420&longitude421",
"click_action":".MessageOrder",
"order":"#421"},
"to":"d2Hxxa6PNYw",
"priority":"high"},{}>
    // after this must be the next step in loop)

Instead of using a loop, you can subscribe users to a specific topic. Then you can send notifications using Firebase Console or writing server-side logic.

FirebaseMessaging.getInstance().subscribeToTopic("news")
    .addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            String msg = getString(R.string.msg_subscribed);
            if (!task.isSuccessful()) {
                msg = getString(R.string.msg_subscribe_failed);
            }
            Log.d(TAG, msg);
            Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
    });

My friend helped me and all working well

@RequestMapping(value = "/sendtodeviceid", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<String> send() throws Exception {
      System.out.println("\n" + "send massege to devicesid" + "\n" + "start to get ID" + "\n");

      ArrayList<String> deviceList = new ArrayList<>();
      Statement statement = jdbcService.getStatement();
      String selSql = String.format("SELECT deviceid FROM courier WHERE isActive = true");
      ResultSet rs = statement.executeQuery(selSql);

      while (rs.next()) {
          String deviceid = rs.getString("deviceid");
          System.out.println("DEVAICE ID which true from sending message " + "\n" + deviceid + "\n");
          deviceList.add(deviceid);
          if (!deviceid.equals(deviceid)) {
              String newdeviceid = deviceid;
              deviceList.add(newdeviceid);
          }
      }
      System.out.println(deviceList + "\n");


      List<CompletableFuture> sentNotifications = new ArrayList<CompletableFuture>();
      for (String deviceId : deviceList) {
          HttpEntity<String> request = new HttpEntity<>(_buildRequestJsonBody(deviceId).toString());

          CompletableFuture<String> pushNotification = androidPushNotificationsService.send(request);
          sentNotifications.add(pushNotification);
      }

      CompletableFuture.allOf(sentNotifications.toArray(new CompletableFuture[sentNotifications.size()])).join();
      for (CompletableFuture<String> notification : sentNotifications) {
          String firebaseResponse = notification.get();
          System.out.println("RESPONSE " + firebaseResponse);

          return new ResponseEntity<>(firebaseResponse, HttpStatus.OK);
      }

      return new ResponseEntity<>("Push Notification ERROR!", HttpStatus.BAD_REQUEST);
  }

  private JSONObject _buildRequestJsonBody(String deviceId) {
      JSONObject body = new JSONObject();
      body.put("to", deviceId);
      body.put("priority", "high");

      JSONObject data = new JSONObject();
      data.put("order", "#421");
      data.put("address", "latitude420&longitude421");
      data.put("click_action", ".MessageOrder");

      body.put("data", data);
      return body;
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM