Уведомление игнорирует настройку тревоги и запускается немедленно - PullRequest
0 голосов
/ 20 октября 2018

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

public class ShowTaskNotificationService extends IntentService {
private Long date_days;
private Long date_time;

public ShowTaskNotificationService() {
    super("ShowTaskNotificationService");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
     date_days = intent.getLongExtra("Date_days",-1);
     date_time = intent.getLongExtra("Date_time",-1);
     return super.onStartCommand(intent, flags, startId);
}

@Override
protected void onHandleIntent(Intent intent) {
    startAlarm();
}
private void startAlarm()
{
    int year,month,day,hour,minute;
    AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

    Calendar calendar_days = Calendar.getInstance();
    calendar_days.setTimeInMillis(date_days);

    Calendar calendar_time = Calendar.getInstance();
    calendar_time.setTimeInMillis(date_time);



    year   = calendar_days.get(Calendar.YEAR);
    month  = calendar_days.get(Calendar.MONTH);
    day    = calendar_days.get(Calendar.DAY_OF_MONTH);
    hour   = calendar_time.get(Calendar.HOUR_OF_DAY);
    minute = calendar_time.get(Calendar.MINUTE);

    //Date date = new Date();
    Calendar cal_alarm = Calendar.getInstance();
    cal_alarm.setTimeInMillis(System.currentTimeMillis());
    //cal_alarm.clear();
    //cal_alarm.setTime(date);
    cal_alarm.set(Calendar.YEAR,year);
    cal_alarm.set(Calendar.MONTH,month);
    cal_alarm.set(Calendar.DAY_OF_MONTH,day);
    cal_alarm.set(Calendar.HOUR_OF_DAY,hour);
    cal_alarm.set(Calendar.MINUTE,minute);


    Intent intent = new Intent(this,AlarmReceiver.class);
    intent.putExtra("cal_alarm",cal_alarm.getTimeInMillis());
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,0);
    alarm.set(AlarmManager.RTC_WAKEUP,cal_alarm.getTimeInMillis(),pendingIntent);


}

}

открытый класс AlarmReceiver extends BroadcastReceiver {privatestatic String CHANNEL_ID = "taskNoti";

@Override
    public void onReceive(Context context, Intent intent) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                CharSequence name = "channel name";
                String description = "channel description";
                int importance = NotificationManager.IMPORTANCE_DEFAULT;
                NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
                channel.setDescription(description);
                NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
                notificationManager.createNotificationChannel(channel);
            }

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("Task time")
                    .setContentText("aaa")
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT);

            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

            notificationManager.notify(12344, mBuilder.build());
            mBuilder.build();

        }

}

public class AlarmReceiver extends BroadcastReceiver {
    private static String CHANNEL_ID = "taskNoti";

@Override
    public void onReceive(Context context, Intent intent) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                CharSequence name = "channel name";
                String description = "channel description";
                int importance = NotificationManager.IMPORTANCE_DEFAULT;
                NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
                channel.setDescription(description);
                NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
                notificationManager.createNotificationChannel(channel);
            }

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("Task time")
                    .setContentText("aaa")
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT);

            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

            notificationManager.notify(12344, mBuilder.build());
            mBuilder.build();

        }

}

Я получаю время из другого фрагмента и передаю его классу ShowTaskNotificationService, а затемполучить его в виде длинных переменных (date_days, date_time)

1 Ответ

0 голосов
/ 20 октября 2018

Сколько времени вы пытаетесь установить?
Как уже упоминалось здесь , если указанное вами время срабатывания уже прошло, сигнал тревоги срабатывает немедленно.Это то, что происходит в вашем случае.Поскольку вы указываете то же время, что и текущее время, в cal_alarm.
Выберите время, в которое вы хотите, чтобы сработала сигнализация.Как то так:

// Set the alarm to start at approximately 2:00 p.m.  
Calendar calendar = Calendar.getInstance();  
calendar.setTimeInMillis(System.currentTimeMillis());  
calendar.set(Calendar.HOUR_OF_DAY, 14);    
// Set the alarm to start at 8:30 a.m.  
Calendar calendar = Calendar.getInstance();  
calendar.setTimeInMillis(System.currentTimeMillis());  
calendar.set(Calendar.HOUR_OF_DAY, 8);  
...