Настройка уведомления о тревоге для массивов дат - PullRequest
1 голос
/ 13 июня 2019

Я пытаюсь создать локальное уведомление, которое будет отклонено до указанной даты на 2 часа, 4 часа и на данную дату. Это мой код, но он не работает:

private void alarmnotification(String notificationid, String type, long timemills) {
    Random rand = new Random();

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(timemills);



    AlarmManager mgrAlarm = (AlarmManager)getSystemService(ALARM_SERVICE);
    ArrayList<PendingIntent> intentArrayd = new ArrayList<PendingIntent>();

    for(int i = 0; i < 4; ++i)
    {
        long timemfills = timemills - 7200000*i ;
        Calendar calendadr = Calendar.getInstance();
        calendadr.setTimeInMillis(timemfills);

        Calendar calendad0r = Calendar.getInstance();
        calendad0r.setTimeInMillis(SystemClock.elapsedRealtime()+calendadr.getTimeInMillis());


        Intent intent = new Intent(getApplicationContext(), NotificationPublisher.class);
        intent.putExtra("type", type);
        intent.putExtra("notificationId", notificationid);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(Home.this, i, intent, 0);

        mgrAlarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timemfills, pendingIntent);

        intentArrayd.add(pendingIntent);


    }
}

А это мой код издателя уведомлений: открытый класс NotificationPublisher расширяет BroadcastReceiver {

public static String NOTIFICATION_ID = "notificationId";
public static String NOTIFICATION = "type";
private LocalBroadcastManager broadcaster;
public void onReceive(Context context, Intent intent) {
    // Get id & message from intent.
    String notificationId = intent.getStringExtra("notificationId");
    String message = intent.getStringExtra("type");
    // When notification is tapped, call MainActivity.
    Intent mainIntent = new Intent(context, Home.class);
    mainIntent.putExtra("retour", message);
    mainIntent.putExtra("element_id", notificationId);
    mainIntent.setAction(Long.toString(System.currentTimeMillis()));
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, mainIntent, 0);

    NotificationManager myNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    // Prepare notification.
    Notification.Builder builder = new Notification.Builder(context);
    builder.setSmallIcon(R.drawable.icoapp_and)
            .setContentTitle(notificationId)
            .setContentText(message)
            .setAutoCancel(true)
            .setContentIntent(contentIntent)
            .setWhen(System.currentTimeMillis())
            .setPriority(Notification.PRIORITY_MAX)
            .setDefaults(Notification.DEFAULT_ALL);

    // Notify
    Random rand = new Random();
    myNotificationManager.notify(rand.nextInt(), builder.build());


}

}

Проблема в том, что я вообще не получаю никаких уведомлений.

Ответы [ 2 ]

0 голосов
/ 13 июня 2019

Попробуй с этим.Так как это вызовет тревогу во время отправки функции и до 2 часов этого времени и 4 часов

и не забудьте добавить канал, так как он не будет работать в Orea или выше

    private void alarmnotification(String notificationid, String type, long timemills) 
    {
    Random rand = new Random();

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(timemills);


    AlarmManager mgrAlarm = (AlarmManager) getSystemService(ALARM_SERVICE);
    ArrayList<PendingIntent> intentArrayd = new ArrayList<PendingIntent>();
    Calendar calendadr = Calendar.getInstance();
    Intent intent;
    PendingIntent pendingIntent;
    for (int i = 0; i < 4; ++i) {
        switch (i) {
            case 1:
                // setting alarm on the specified Date
                calendadr.setTimeInMillis(timemills);
                intent = new Intent(this, NotificationPublisher.class);
                intent.putExtra("type", type);
                intent.putExtra("notificationId", notificationid);
                pendingIntent = PendingIntent.getBroadcast(Home.this, rand, intent, 0);
                mgrAlarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, calendadr.getTimeInMillis(), pendingIntent);
                intentArrayd.add(pendingIntent);
                break;
            case 2:
                // setting alarm 2 hours earlier of the date
                calendadr.setTimeInMillis(timemills);
                // deducting 2 hours
                calendadr.set(Calendar.HOUR_OF_DAY, -2);
                intent = new Intent(this, NotificationPublisher.class);
                intent.putExtra("type", type);
                intent.putExtra("notificationId", notificationid);
                pendingIntent = PendingIntent.getBroadcast(Home.this, rand, intent, 0);
                mgrAlarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, calendadr.getTimeInMillis(), pendingIntent);
                intentArrayd.add(pendingIntent);
                break;
            case 3:
                // setting alarm 2 hours earlier of the date
                calendadr.setTimeInMillis(timemills);
                // deducting 2 hours
                intent = new Intent(this, NotificationPublisher.class);
                calendadr.set(Calendar.HOUR_OF_DAY, -4);
                intent.putExtra("type", type);
                intent.putExtra("notificationId", notificationid);
                pendingIntent = PendingIntent.getBroadcast(Home.this, rand, intent, 0);
                mgrAlarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, calendadr.getTimeInMillis(), pendingIntent);
                intentArrayd.add(pendingIntent);

                break;
        }

    }
}
0 голосов
/ 13 июня 2019

Если вы работаете на Android 8.0 (уровень API 26) или выше, вы должны создать канал уведомлений для получения уведомления.

private void createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

Для полной документации, пожалуйста, перейдите по этой ссылке: Создание и управление каналами уведомлений

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...