Как сделать так, чтобы появлялось одно уведомление, а через интервал уже другое? (Android Java)

232
05 мая 2018, 17:46

Пытаюсь сделать уведомления в Android Studio. Мне нужно сделать так, чтобы сначала появилось одно уведомление, затем, минуя один интервал, появилось уже другое уведомление, и, минуя ещё один интервал, вылезло третье. Здесь пока только 2 уведомления, но второе появляться не хочет. Что я делаю не так? Время менялось несколько раз.

public class FirstCompetitionActivity extends AppCompatActivity {
AlarmManager alarmManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_first_competition);
    findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Calendar calendar1 = Calendar.getInstance();

            Intent intent1 = new Intent(getApplicationContext(), NotificationReceiver1.class);
            PendingIntent pendingIntent1 = PendingIntent.getBroadcast(getApplicationContext(), 100, intent1, PendingIntent.FLAG_CANCEL_CURRENT);
            alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), pendingIntent1);
            Calendar calendar2 = Calendar.getInstance();
            calendar2.set(2018, 5, 4, 13, 38);
            Intent intent2 = new Intent(getApplicationContext(), NotificationReceiver2.class);
            PendingIntent pendingIntent2 = PendingIntent.getBroadcast(getApplicationContext(), 101, intent2, PendingIntent.FLAG_CANCEL_CURRENT);
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar2.getTimeInMillis(), pendingIntent2);
        }
    });
  }
}

Ресивер1:

public class NotificationReceiver1 extends BroadcastReceiver {
private static final String CHANNEL_ID = "CHANNEL_ID";
@Override
public void onReceive(Context context, Intent intent) {
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    Intent repeatingIntent = new Intent(context, FirstCompetitionActivity.class);
    repeatingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context.getApplicationContext(), CHANNEL_ID)
            .setContentIntent(pendingIntent)
            .setSmallIcon(R.drawable.i1)
            .setContentTitle("Уведомление")
            .setContentText("Вы приняли участие во всероссийском литературном конкурсе \"Автограф юного писателя\"! " +
                    "Своевременно выполняйте задания. Мы желаем Вам успеха!")
            .setAutoCancel(false);
    createChannelIfNeeded(notificationManager);
    notificationManager.notify(100, builder.build());
}
private void createChannelIfNeeded(NotificationManager notificationManager) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_ID, NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(notificationChannel);
    }
  }
}

Ресивер2 практически идентичен:

public class NotificationReceiver2 extends BroadcastReceiver {
private static final String CHANNEL_ID = "CHANNEL_ID";
@Override
public void onReceive(Context context, Intent intent) {
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    Intent repeatingIntent = new Intent(context, FirstCompetitionActivity.class);
    repeatingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 101, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context.getApplicationContext(), CHANNEL_ID)
            .setContentIntent(pendingIntent)
            .setSmallIcon(R.drawable.i1)
            .setContentTitle("Уведомление")
            .setContentText("Не забудьте скачать задания!")
            .setAutoCancel(false);
    createChannelIfNeeded(notificationManager);
    notificationManager.notify(101, builder.build());
}
private void createChannelIfNeeded(NotificationManager notificationManager) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_ID, NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(notificationChannel);
    }
  }

}

READ ALSO
Паттерн в DecimalFormatSymbols

Паттерн в DecimalFormatSymbols

Используя такой формат

204
Анализ/парсинг .java файла

Анализ/парсинг .java файла

Стоит задача проанализировать файлы с расширениемjava начиная с корневого пакета проекта и построить зависимости на основании используемых...

137
Почему возникает ошибка “Validation failed for object='product'”?

Почему возникает ошибка “Validation failed for object='product'”?

Делаю веб приложение на Java c использованием Spring MVC, Spring Security и HibernateКогда хочу добавить продукт меня дает такая ошибка

249