Android: как исправить приращение setNumber () для уведомления? - PullRequest
0 голосов
/ 14 мая 2018

Я использую JobIntentService, запущенный с BroadcastReceiver, чтобы отправить пользователю Уведомление о приближении срока оплаты. Когда следующее Уведомление о другой дате выполнения уже близко, я просто хочу обновить существующее Уведомление и увеличить индикатор setNumber () на +1. Первое уведомление корректно увеличивает переменную totalMesssages на +1, а setNumber () показывает «1» в раскрывающемся диалоговом окне «Уведомление». Следующее уведомление срабатывает корректно, но setNumber () не увеличивается на +1 до «2». Это остается в "1".

Что мне здесь не хватает?

public class AlarmService extends JobIntentService {

    static final int JOB_ID = 9999;
    private int totalMessages = 0;

    static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, AlarmService.class, JOB_ID, work);
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent) {

    sendNotification();
    }

    private void sendNotification() {

        int notifyID = 1;

        NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);

        if (notificationManager != null) {
         notificationManager.createNotificationChannel(notificationChannel);
        }
    }

    NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
        .setDefaults(Notification.DEFAULT_ALL)
        .setSmallIcon(R.drawable.ic_announcement_white_24dp)
        .setContentText("")
        .setNumber(++totalMessages);

    Intent intent = new Intent(this, MainActivity.class);        
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(contentIntent);
    mBuilder.setAutoCancel(true);;

    if (notificationManager != null) {
        notificationManager.notify(notifyID, mBuilder.build());
    }
  }
}   

1 Ответ

0 голосов
/ 14 мая 2018
private int totalMessages = 0;

Инициализируется равным 0 каждый раз, когда JobIntentService запускается из BroadcastReceiver.

Одним из решений является сохранение totalMessage в SharedPreferences и использование его в AlarmService.

SharedPreferences sp = getApplicationContext().getSharedPreferences("preferences_name", Context.MODE_PRIVATE);
int totalMessages = sp.getInt("total-messages", 0); //initialize to 0 if it doesn't exist
SharedPreferences.Editor editor = sp.edit();
editor.putInt("total-messages",++totalMessages);
editor.apply();

Вы можете вставить это непосредственно перед создателем уведомлений в своем коде.

...