2017-05-30 1 views
0

J'ai un service qui Configurations de l'AlarmManager comme indiqué:Alarm Manager ne se déclenche pas une émission

private void setupInsuranceNotification(@NonNull String plate, @NonNull LocalDate insuranceDeadline) 
    { 
     LocalDate now = LocalDate.now(); 
     int daysToDeadline = getDaysBetweenDates(now, insuranceDeadline); 
     String notificationTitle = "Assicurazione " + plate; 
     String notificationMessage; 
     int millsBetweenNotifications = 1000 * 60 * 60 * 24; // 1 day default 
     LocalDate notificationStart = now; 

     if (daysToDeadline > 0) 
     { 
      notificationMessage = daysToDeadline + " giorni alla scadenza."; 

      if (daysToDeadline > 30) 
      { 
       // show the notification only when they are 30 days left 
       notificationStart = now.withFieldAdded(DurationFieldType.days(), daysToDeadline - 30); 
      } 
     } 
     else if (daysToDeadline == 0) 
     { 
      notificationMessage = "Assicurazione scaduta oggi."; 
     } 
     else 
     { 
      if (daysToDeadline >= -15) 
      { 
       // tolerance period 
       notificationMessage = Math.abs(daysToDeadline) + " alla fine del periodo di tolleranza!"; 
       millsBetweenNotifications = 1000 * 60 * 60 * 6; // 6 hours 
      } 
      else 
      { 
       // insurance expired 
       notificationMessage = "Periodo di tolleranza finito! L'assicurazione è scaduta!"; 
       millsBetweenNotifications = 1000 * 60 * 60; // 1 hour 
      } 
     } 

     Intent notificationIntent = new Intent(this, NotificationPublisher.class); 
     notificationIntent.putExtra("notification_title", notificationTitle); 
     notificationIntent.putExtra("notification_message", notificationMessage); 
     PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 
     AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
     alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, notificationStart.toDate().getTime(), millsBetweenNotifications, alarmIntent); 
    } 

ceci est ma NotificationPublisher classe:

public class NotificationPublisher extends BroadcastReceiver 
{ 
    private static final int NOTIFICATION_ID = 1; 

    @Override 
    public void onReceive(Context context, Intent intent) 
    { 
     String title = intent.getStringExtra("notification_title"); 
     String message = intent.getStringExtra("notification_message"); 
     Notification.Builder builder = new Notification.Builder(context); 
     NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 

     builder.setContentTitle(title); 
     builder.setContentText(message); 
     builder.setSmallIcon(R.drawable.ic_notification); 
     manager.notify(NOTIFICATION_ID, builder.build()); 
    } 
} 

Mon problème est que le setupInsuranceNotification est correctement exécuté jusqu'à la fin (il n'y a pas d'exception), mais mon NotificationPublisher n'est jamais viré (j'ai mis un point d'arrêt pour vérifier).

EDIT

c'est mon onHandleIntent de NotificationService classe:

@Override 
    protected void onHandleIntent(@Nullable Intent intent) 
    { 
     Debug.waitForDebugger(); 

     if (Utilities.vehicleFileExists(this)) 
     { 
      try 
      { 
       DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
       DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
       Document doc = dBuilder.parse(Utilities.getVehicleListFile(this)); 
       Element root = doc.getDocumentElement(); 

       root.normalize(); 

       NodeList vehicleNodeList = root.getElementsByTagName("vehicle"); 

       for (int i = 0; i < vehicleNodeList.getLength(); i++) 
       { 
        Element vehicleElement = (Element) vehicleNodeList.item(i); 
        Element matriculationDateElement = (Element) vehicleElement.getFirstChild(); 
        Element endInsuranceDateElement = (Element) matriculationDateElement.getNextSibling(); 
        Element lastInspectionDateElement = (Element) endInsuranceDateElement.getNextSibling(); 

        String plate = vehicleElement.getAttribute("plate"); 
        LocalDate matriculationDate = LocalDate.parse(matriculationDateElement.getFirstChild().getNodeValue(), DateTimeFormat.forPattern(Utilities.Formats.Date.ITALIAN)); 
        LocalDate endInsuranceDate = LocalDate.parse(endInsuranceDateElement.getFirstChild().getNodeValue(), DateTimeFormat.forPattern(Utilities.Formats.Date.ITALIAN)); 
        LocalDate lastInspectionDate = null; 

        if (lastInspectionDateElement.getFirstChild() != null) // <inspection_dates/> 
        { 
         lastInspectionDate = LocalDate.parse(lastInspectionDateElement.getFirstChild().getNodeValue(), DateTimeFormat.forPattern(Utilities.Formats.Date.ITALIAN)); 
        } 

        LocalDate inspectionDeadline = getInspectionDeadline(matriculationDate, lastInspectionDate); 

        setupInsuranceNotification(plate, endInsuranceDate); 
        setupInspectionNotification(plate, inspectionDeadline); 
       } 
      } 
      catch (ParserConfigurationException | SAXException | IOException ignored) {} 
     } 
    } 
+0

Avez-vous Registerd le récepteur dans le Manifest? – MatPag

+0

@MatPag oui: ' ' – Clyky

+0

Vous devriez essayer de remplacer votre code AlarmManager par celui-ci [ici] (https://stackoverflow.com/a/31838628/ 2910520) et voir si cela fonctionne. De cette façon, nous pouvons dire avec certitude que le problème est l'intention ou l'AlarmManager de votre code et pas autre chose – MatPag

Répondre

1

Votre NotificationPublisher est tiré seulement pour last itération à cause de même requestCode que vous avez utilisé en alarme PendingIntent.

Comme vous utilisez requestCode comme 0 pour toutes les alarmes, il remplace simplement l'alarme précédente data. C'est pourquoi seulement pour last alarme onReceive() de votre NotificationPublisher exécuté.

SOLUTION:

Utiliser une autre REQUEST_CODE pour alarme différentes PendingIntent.

PendingIntent alarmIntent = PendingIntent.getBroadcast(this, REQUEST_CODE, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

Espérons que cela aidera ~

+0

merci beaucoup, j'ai compris où le problème était :) mais j'ai une autre question: j'ai résolu le problème dans (je pense) d'une manière brutale, en utilisant 'Random' pour générer des identifiants aléatoires. Est-ce correct? Et puis, y a-t-il un autre moyen intelligent d'envoyer un groupe de notifications? – Clyky

+0

Je pense qu'il n'y a pas d'autre moyen. L'essentiel est que vous ayez à définir un code de requête unique pour chaque alarme. Pour faire une alarme multiple, vous devez utiliser une technique de bouclage. – FAT

+0

S'il n'est pas possible de déclencher plusieurs alarmes en même temps, vous pouvez créer une seule alarme avec répétition au lieu de créer plusieurs alarmes. J'espère que vous comprenez :) – FAT