0
\$\begingroup\$

PREMISE:

I have zero knowledge of Java and Android development. I put this together in a couple of weeks. The code works. But I look forward to some feedback and to know how I can improve it.

DESCRIPTION:

I need to send push notifications to a group of users.

I am using OneSignal with the OneSignal Cordova SDK.

When the first user click the action button, I cancel the previously sent notification from all others users devices (the action button is handled in js with the cordova plugin).

To cancel the notification from the device I send a background notification with the id of the notification to cancel to that group of users.

I wrote a service in Java that extend the OneSignal NotificationExtenderService.

It checks the notification type. If it's a normal notification, I will make a POST request to my API to save some data about the notification, including the androidNotificationId (that I will need later if I have to cancel it).

If the notification is silent, I get the id of the notification that has to be cancelled, and I delete it using the notificationManager.cancel() method.

THE CODE:

public class NotificationService extends NotificationExtenderService {

  @Override
  protected boolean onNotificationProcessing(OSNotificationReceivedResult receivedResult) {

    Context ctx = getApplicationContext();

    JSONObject additionalData = receivedResult.payload.additionalData;
    final String notificationType = additionalData.optString("notification_type");

    if (notificationType.equals("silent")) {
      // If notification type is 'silent' then it's a background notification
      try {
        int notificationIdToCancel = additionalData.getInt("notification_id_to_cancel");

        NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(notificationIdToCancel);

        return true; // in this way the background notification is not displayed to the device

      } catch (JSONException e) {
        //some exception handler code.
      }

      return true;

    } else {

      // Active notification - to be displayed
      final String tableNumber = additionalData.optString("table_number");
      final String customId = additionalData.optString("notification_id_custom");
      final String projectId = additionalData.optString("project_id");

      // Override notification builder - for design only
      OverrideSettings overrideSettings = new OverrideSettings();
      overrideSettings.extender = new NotificationCompat.Extender() {
        @Override
        public NotificationCompat.Builder extend(NotificationCompat.Builder builder) {
          // Sets the background notification color to Green on Android 5.0+ devices.
          return builder.setColor(Color.parseColor("#7BE1B1"))
                 .setSmallIcon(R.mipmap.icon)
                 .setBadgeIconType(NotificationCompat.BADGE_ICON_LARGE);
        }
      };

      OSNotificationDisplayedResult displayedResult = displayNotification(overrideSettings);
      Log.d("OneSignal", "Notification displayed with id: " + displayedResult.androidNotificationId);

     // Make POST request - with notification data
     try{
       URL url = new URL("http://MYAPI.com/save_notification");

        try{
          // Init connection
          URLConnection con = url.openConnection();
          HttpURLConnection http = (HttpURLConnection)con;
          http.setRequestMethod("POST"); // PUT is another valid option
          http.setDoOutput(true);

          // Data to send to API
          String dataApi = "{\"notification_id_custom\":\"" + customId + "\",\"project_id\":\"" + projectId + "\",\"android_notification_id\":\"" + displayedResult.androidNotificationId + "\"}";

          // Send JSON request
          byte[] out = dataApi.getBytes(StandardCharsets.UTF_8);
          int length = out.length;

          http.setFixedLengthStreamingMode(length);
          http.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
          http.connect();
          try(OutputStream os = http.getOutputStream()) {
            os.write(out);
            os.flush();
            os.close();

            // Get response from API - for debug only
            int responseCode = http.getResponseCode();
            System.out.println("POST Response Code : " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) { //success
              BufferedReader in = new BufferedReader(new InputStreamReader(
                http.getInputStream()));
              String inputLine;
              StringBuffer response = new StringBuffer();

              while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
              }
              in.close();
              System.out.println(response.toString());
            } else {
              System.out.println("POST request not worked");
            }

            return false; // in this way the notification is going to be displayed in the device
          }
        }catch(IOException ex){
          // exception handling here
        }
      }catch(MalformedURLException ex){
        //do exception handling here
      }
      return false;
    }

  }
}
\$\endgroup\$

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.