Один и тот же идентификатор для другого уведомления - PullRequest
0 голосов
/ 15 мая 2018

Я реализовал приложение, которое работает с уведомлениями, которые устанавливаются программно, с такими кодами:

 public void setAlarm(Cell cell, Long timeStamp, String title, String message) {
    Integer id = (int) System.currentTimeMillis();
    Intent notificationIntent = new Intent(context, receiver);
    notificationIntent.putExtra("ID", id);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, id, notificationIntent, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    assert alarmManager != null;
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, timeStamp, 2 * 60 * DateUtils.SEC_TO_MILLIS, pendingIntent);
    RepositoryManager repositoryManager = RepositoryManager.getInstance();
    repositoryManager.storeNotificationAdministration(new NotificationAdministration(id, timeStamp, 2, title, message, 1, null, cell, StatusNotification.NOT_YET_NOTIFIED.getId()));
}

Это мой приемник:

 @Override
public void onReceive(Context context, Intent intent) {
    RepositoryManager controllerDatabase = RepositoryManager.getInstance(ControllerDatabase.getInstance(context));
    NotificationMedicine notificationMedicine = controllerDatabase.getNotificationMedicine();
    if (notificationMedicine.getEnable()) {
        if (intent.hasExtra("ID")) {
            int id = intent.getIntExtra("ID", 0);
            NotificationManager mNotifyMgr =
                    (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            Log.d("DEBUG", "MyReceiverAdministration " + id);
            try {
                NotificationAdministration notificationAdministration = controllerDatabase.findNotificationAdministrationById(id);

                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.ic_medicine)
                        .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
                        .setContentTitle(notificationAdministration.getTitle())
                        .setContentText(notificationAdministration.getMessage())
                        .setOngoing(false)
                        .setPriority(NotificationCompat.PRIORITY_HIGH)
                        .setAutoCancel(false);

                Intent i = new Intent(context, MainActivity.class);
                i.putExtra(SettingsData.TAG_CELL, notificationAdministration.getCell().getId());
                PendingIntent pendingIntent =
                        PendingIntent.getActivity(
                                context,
                                notificationAdministration.getId(),
                                i,
                                0
                        );
                Intent snoozeIntent = new Intent(context, MyFlagBroadcastReceiver.class);
                snoozeIntent.putExtra(SettingsData.TAG_CELL, notificationAdministration.getId());
                PendingIntent flagIt =
                        PendingIntent.getBroadcast(context, 0, snoozeIntent, 0);
                mBuilder.setLights(0x6098CF, 1000, 2000);
                Uri uriRingtone = notificationMedicine.getRingtone();
               mBuilder.setSound(uriRingtone);
                mBuilder.setContentIntent(pendingIntent);
                mBuilder.addAction(R.drawable.ic_timer_black_24dp, context.getString("Do my action"), flagIt);
                mNotifyMgr.notify(notificationAdministration.getId(), mBuilder.build());
                Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                v.vibrate(700);
                notificationAdministration.setStatus(StatusNotification.NOTIFIED.getId());
                controllerDatabase.storeNotificationAdministration(notificationAdministration);
            } catch (ObjectNotFoundException e) {
                e.printStackTrace();
            }
            }
        }
    }
}

Это другой получатель, когда пользователь нажимает на действие уведомления:

 RepositoryManager controllerDatabase = RepositoryManager.getInstance(ControllerDatabase.getInstance(context));
        if (intent.hasExtra(SettingsData.TAG_CELL)) {
            int id = intent.getIntExtra(SettingsData.TAG_CELL, 0);
try {
                NotificationAdministration notificationAdministration = controllerDatabase.findNotificationAdministrationById(id);
                Device device = controllerDatabase.getDefaultDeviceByUser(controllerDatabase.getLoggedUser().getUser());
                Cell cell = controllerDatabase.findCellById(device, notificationAdministration.getCell().getId());
                Calendar calendar = Calendar.getInstance();
                Long now = calendar.getTimeInMillis() / DateUtils.SEC_TO_MILLIS;
                controllerDatabase.flagMedicineTaken(cell, now);
                NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                if (mNotificationManager != null) {
                    mNotificationManager.cancel(id);
                }
            } catch (ObjectNotFoundException e) {
                e.printStackTrace();
            }
        }

Проблема, с которой я сталкиваюсь, заключается в том, что MyFlagBoradcastReceiver всегда получает один и тот же идентификатор уведомления, а не тот, который я нажимаю / нажимаю.

Идея приложения состоит в том, чтобы устанавливать различные уведомления, которые всегда видны, если пользователь не нажимает на действие уведомления. Тревога должна быть активирована также через 2 минуты ...

** ОБНОВЛЕНИЕ **

Это строки кода, которые я должен использовать для отмены тревоги; что я должен использовать в качестве приемника?

AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            Intent myIntent = new Intent(context,
                    receiver);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(
                    context, notificationAdministration.getId(), myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            if (alarmManager != null) {
                alarmManager.cancel(pendingIntent);
            }

1 Ответ

0 голосов
/ 15 мая 2018

При создании PendingIntent для Notification необходимо сделать следующее:

PendingIntent flagIt = PendingIntent.getBroadcast(context,
                         notificationAdministration.getId(),
                         snoozeIntent, 0);

Вам необходимо убедиться, что каждый PendingIntent, который вы создаете для MyFlagBroadcastReceiver, уникален, иначе Android просто вернет существующий PendingIntent вместо создания нового. Вы можете сделать это, предоставив уникальный идентификатор для каждого звонка PendingIntent.getBroadcast().

...