2016-04-27 2 views
2

У меня есть событие календаря с стартовая дата как (формат 24 часа) 27-апр-2016 11:00:00 и дата окончания как 29-апр-2016 11:00:00. У меня есть три тайминга 10:45:00, 10:30:00 и 10:15:00, которые рассчитываются для оповещения о событии до фактических установленных таймингов (т.е. 15 минут, 30 минут и 45 минут мин до начала даты).Настройка сигнала тревоги для определенных сроков в отношении даты начала и окончания даты в Android

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

Вот как я пытался сделать это, как всегда ниже код не вызывает тревогу и не повторяет ежедневно

В MainActivity.java

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
Intent intent = new Intent(this, Broadcast.class); 
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

Calendar calendar = Calendar.getInstance(); 
calendar.set(2016,03,27,11,00,00); 
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()-(60000*15), pendingIntent); // subtract for 15 mins prior alarm time 
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()-(60000*30), pendingIntent); // subtract for 30 mins prior alarm time 
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()-(60000*45), pendingIntent); // subtract for 45 mins prior alarm time 

В Broadcast. java

Log.i("Alarm", "Alarm Manager is called"); 
Toast.makeText(context, new Date().toString(), Toast.LENGTH_SHORT).show(); 

Как я могу это достичь? Пожалуйста, помогите

+0

В BroadCast.java вы используете WakefulBroadcast Recevier @Waseem – Lampard

+0

да? его класс расширяется in BroadcastReceiver @CrazyAndroid –

+0

В этом случае я прошу вас продлить WakefulBroadcastReceiver, потому что это гарантирует, что ваш процессор будет бодрствовать до тех пор, пока вы не запустите fullWakefulIntent. – Lampard

ответ

2

Вот мой пример кода, Попробуйте это:

Изменить дату и время как ваша потребность в коде ниже.

public static int REPEAT_NOTIFICATION1 = 201; 
    public static int REPEAT_NOTIFICATION2 = 202; 
    public static int REPEAT_NOTIFICATION3 = 203; 

    private void repeatNotification() { 
     final DateTime dateTime1 = DateTime.now(); 
     dateTime1.hourOfDay().setCopy(7); 
     dateTime1.minuteOfHour().setCopy(30); 
     dateTime1.secondOfMinute().setCopy(00); 
     final Calendar calendarNotifiedTime1 = Calendar.getInstance(); 
     calendarNotifiedTime1.set(Calendar.HOUR, dateTime1.getHourOfDay()); 
     calendarNotifiedTime1.set(Calendar.MINUTE, dateTime1.getMinuteOfHour()); 
     calendarNotifiedTime1.set(Calendar.SECOND, dateTime1.getSecondOfMinute()); 
     calendarNotifiedTime1.set(Calendar.AM_PM, Calendar.AM); 

     final DateTime dateTime2 = DateTime.now(); 
     dateTime2.hourOfDay().setCopy(12); 
     dateTime2.minuteOfHour().setCopy(30); 
     dateTime2.secondOfMinute().setCopy(00); 
     final Calendar calendarNotifiedTime2 = Calendar.getInstance(); 
     calendarNotifiedTime2.set(Calendar.HOUR, dateTime2.getHourOfDay()); 
     calendarNotifiedTime2.set(Calendar.MINUTE, dateTime2.getMinuteOfHour()); 
     calendarNotifiedTime2.set(Calendar.SECOND, dateTime2.getSecondOfMinute()); 
     calendarNotifiedTime2.set(Calendar.AM_PM, Calendar.PM); 

     final DateTime dateTime3 = DateTime.now(); 
     dateTime3.hourOfDay().setCopy(6); 
     dateTime3.minuteOfHour().setCopy(30); 
     dateTime3.secondOfMinute().setCopy(00); 
     final Calendar calendarNotifiedTime3 = Calendar.getInstance(); 
     calendarNotifiedTime3.set(Calendar.HOUR, dateTime3.getHourOfDay()); 
     calendarNotifiedTime3.set(Calendar.MINUTE, dateTime3.getMinuteOfHour()); 
     calendarNotifiedTime3.set(Calendar.SECOND, dateTime3.getSecondOfMinute()); 
     calendarNotifiedTime3.set(Calendar.AM_PM, Calendar.PM); 


     Intent intent1 = new Intent(EmptyActivity.this, NotificationReceiver.class); 
     intent1.putExtra(NotificationReceiver.NOTIFICATION_MESSAGE, "Repeat " + dateTime1.getHourOfDay() + ":" + dateTime1.getMinuteOfHour() + ":" + dateTime1.getSecondOfMinute()); 
     Intent intent2 = new Intent(EmptyActivity.this, NotificationReceiver.class); 
     intent2.putExtra(NotificationReceiver.NOTIFICATION_MESSAGE, "Repeat " + dateTime2.getHourOfDay() + ":" + dateTime2.getMinuteOfHour() + ":" + dateTime2.getSecondOfMinute()); 
     Intent intent3 = new Intent(EmptyActivity.this, NotificationReceiver.class); 
     intent3.putExtra(NotificationReceiver.NOTIFICATION_MESSAGE, "Repeat " + dateTime3.getHourOfDay() + ":" + dateTime3.getMinuteOfHour() + ":" + dateTime3.getSecondOfMinute()); 
     PendingIntent pendingIntent1 = PendingIntent.getBroadcast(EmptyActivity.this, REPEAT_NOTIFICATION1, intent3, PendingIntent.FLAG_UPDATE_CURRENT); 
     PendingIntent pendingIntent2 = PendingIntent.getBroadcast(EmptyActivity.this, REPEAT_NOTIFICATION2, intent2, PendingIntent.FLAG_UPDATE_CURRENT); 
     PendingIntent pendingIntent3 = PendingIntent.getBroadcast(EmptyActivity.this, REPEAT_NOTIFICATION3, intent3, PendingIntent.FLAG_UPDATE_CURRENT); 
     AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE); 


       cancelNotification(REPEAT_NOTIFICATION1); 
     alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendarNotifiedTime1.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent1); 
       cancelNotification(REPEAT_NOTIFICATION2); 
     alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendarNotifiedTime2.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent2); 
       cancelNotification(REPEAT_NOTIFICATION3); 
     alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendarNotifiedTime3.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent3); 
    } 

Отменить Извещение:

public void cancelNotification(int requestCode) { 
      try { 
       Intent notificationIntent = new Intent(getApplicationContext(), NotificationReceiver.class); 
       PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), requestCode, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 
       AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); 
       alarmManager.cancel(pendingIntent); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 

радиовещательный приемник:

public class NotificationReceiver extends BroadcastReceiver { 
    public static String NOTIFICATION_MESSAGE = "notificationMessage"; 
    public static int REPEAT_NOTIFICATION1 = 201; 
    public static int REPEAT_NOTIFICATION2 = 202; 
    public static int REPEAT_NOTIFICATION3 = 203; 

    Context context; 

    @Override 
    public void onReceive(Context context, Intent intent) { 

     this.context = context; 

     //Assume StartDate = yesterday. 
     DateTime startDate = DateTime.now().minusDays(1); 
     //Assume EndDate = tomorrow 
     DateTime endDate = startDate.plusDays(2); 

     DateTime today = DateTime.now(); 

     if (today.isBefore(endDate) || today.isEqual(endDate)) { 

      String message = intent.getStringExtra(NOTIFICATION_MESSAGE); 
      NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
      //Define sound URI 
      Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 

      Intent notificationIntent = new Intent(context, EmptyActivity.class); 
      notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); 

      PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); 
      final DateTime dateTime = DateTime.now(); 
      int color = 0xffffaa00; 
//  int color1 = context.getColor(R.color.notificatinBackgroundColor); 
      NotificationCompat.Builder builder = new NotificationCompat.Builder(context); 
      builder.setSmallIcon(R.drawable.festi_push_message_small); 
      builder.setContentIntent(pendingIntent); 
      builder.setContentTitle("Notification Sample"); 
      builder.setAutoCancel(true); 
      builder.setContentText(message + ", Current Time : " + dateTime.getHourOfDay() + ":" + dateTime.getMinuteOfHour() + ":" + dateTime.getSecondOfMinute()); 
      builder.setSound(soundUri); 
      builder.setLights(Color.RED, 1000, 1000); 
      builder.setColor(color); 

      Notification notification = builder.build(); 

      notification.flags |= Notification.FLAG_AUTO_CANCEL; 

      notificationManager.notify(102938, notification); 
     } else { 
      cancelNotification(REPEAT_NOTIFICATION1); 
      cancelNotification(REPEAT_NOTIFICATION2); 
      cancelNotification(REPEAT_NOTIFICATION3); 
     } 
    } 

    public void cancelNotification(int requestCode) { 
     try { 
      Intent notificationIntent = new Intent(context, NotificationReceiver.class); 
      PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 
      AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
      alarmManager.cancel(pendingIntent); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

} 

Manifest.xml

<receiver android:name=".NotificationReceiver" /> 
+0

Привет @Sabir вы можете показать мне код для DateTime.java? –

+0

Привет @Sabari я попытался с кодом, но я, кажется, не получаю уведомление, также это поможет мне в настройке аварийных сигналов событий для каждого события, которое я создаю? –

+0

Привет @WaseemAkram, здесь я использую Joda DateTime – Sabari

Смежные вопросы