2016-07-14 3 views
0

Я делаю систему отслеживания посещаемости. Итак, мне нужно активировать уведомления до начала класса и после запуска класса.Несколько уведомлений, только первый загорается

Главный метод - это то, где я создаю уведомления для каждого курса из базы данных. Метод

mainMethod() { 
    testAlarmA(s[0], s[2]); 
    testAlarmB(s[0], s[2]); 
} 

Я реализовал SetAction() для каждого намерения, а также имеют различные коды запроса для каждого отложенного намерения (я прочитал их в более ранних вопросах на этом сайте)

private void testAlarmA (String code) { 
    Log.i("attendance", "class-start"); 
    AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE); 

    Intent notificationIntent = new Intent("android.media.action.DISPLAY_ATTENDANCE_NOTIFICATION"); 
    notificationIntent.addCategory("android.intent.category.DEFAULT"); 
    notificationIntent.putExtra("type", "start"); 
    notificationIntent.putExtra("courseCode", code); 
notificationIntent.setAction(Long.toString(System.currentTimeMillis())); 

    Calendar c = Calendar.getInstance(); 
    c.add(Calendar.MINUTE, 1); 

    PendingIntent broadcast = PendingIntent.getBroadcast(getContext(), 111, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), (2 * 60 * 1000), broadcast); 
} 

private void testAlarmB (String code){ 
    Log.i("attendance", "class-end"); 
    AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE); 

    Intent notificationIntent = new Intent("android.media.action.DISPLAY_ATTENDANCE_NOTIFICATION"); 
    notificationIntent.addCategory("android.intent.category.DEFAULT"); 
    notificationIntent.putExtra("type", "end"); 
    notificationIntent.putExtra("courseCode", code); 
    notificationIntent.setAction(Long.toString(System.currentTimeMillis())); 

    Calendar c = Calendar.getInstance(); 
    c.add(Calendar.MINUTE, 2); 

    PendingIntent broadcast = PendingIntent.getBroadcast(getContext(), 222, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), (2 * 60 * 1000), broadcast); 

} 

В ВЕЩАТЕЛЬНОМ класс приемника, я извлекаю дополнительные функции, чтобы узнать, какое уведомление нужно запустить, т. е. начало или конец класса.

Но только класс start notif является приемником, класс end Запись в журнал никогда не отображается.

@Override 
public void onReceive(Context context, Intent intent) { 
    Log.i("time", "onReceive"); 
    mNotificationManager = 
      (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
    manager = mNotificationManager; 

     if (intent.getExtras().containsKey("type")) { 
      Log.i("time", "containsKey"); 

      String type = intent.getExtras().getString("type"); 
      if (type.equals("end")) { 
       Log.i("time", "end"); 
       endNotif(context); 

      } else if (type.equals("start")) { 
       Log.i("time", "start"); 
       startNotif(context); 

      } 
    } 

} 

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

private void startNotif (Context context) { 
    Intent notificationIntent = new Intent(); 
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); 
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) 
      .setContentTitle("You Have " + courseCode + " at " + roomNo) 
      .setContentIntent(pendingIntent) 
      .setDefaults(Notification.DEFAULT_VIBRATE) 
      .setPriority(Notification.PRIORITY_DEFAULT) 
      .setVisibility(Notification.VISIBILITY_PUBLIC) 
      .setSmallIcon(R.drawable.ic_library_books_white_24dp) 
      .setLights(0xff00ff00, 1000, 1000) 
      .setAutoCancel(true); 

    mNotificationManager.notify(1, mBuilder.build()); 
} 

В моем уведомлении о конечном классе будет три кнопки действий.

private void endNotif (Context context) { 
    Intent notificationIntent = new Intent(context, AttendanceActivity.class); 
    notificationIntent.putExtra("courseCode", courseCode); 
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); 

    Intent classAttended = new Intent(context, AttendanceNotificationServiceClass.class); 
    classAttended.setAction("action"); 
    classAttended.putExtra("courseCode", courseCode); 
    classAttended.putExtra("class", "attended"); 
    PendingIntent pClassAttended = PendingIntent.getService(context, 11, classAttended, PendingIntent.FLAG_UPDATE_CURRENT); 

    Intent classBunked = new Intent(context, AttendanceNotificationServiceClass.class); 
    classBunked.setAction("action"); 
    classBunked.putExtra("courseCode", courseCode); 
    classBunked.putExtra("class", "bunked"); 
    PendingIntent pClassBunked = PendingIntent.getService(context, 22, classBunked, PendingIntent.FLAG_UPDATE_CURRENT); 

    Intent classOff = new Intent(context, AttendanceNotificationServiceClass.class); 
    classOff.setAction("action"); 
    classOff.putExtra("courseCode", courseCode); 
    classOff.putExtra("class", "off"); 
    PendingIntent pClassOff = PendingIntent.getService(context, 33, classOff, PendingIntent.FLAG_UPDATE_CURRENT); 

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) 
      .setVisibility(Notification.VISIBILITY_PUBLIC) 
      .setSmallIcon(R.drawable.ic_library_books_white_24dp) 
      .setContentTitle(courseCode + " Just Ended") 
      .setContentText("Did you attend " + courseCode + " ?") 
      .addAction(R.drawable.ic_thumb_up_white_24dp, "Attended", pClassAttended) 
      .addAction(R.drawable.ic_thumb_down_white_24dp, "Bucked", pClassBunked) 
      .addAction(R.drawable.ic_clear_white_24dp, "Class Off", pClassOff) 
      .setContentIntent(pendingIntent) 
      .setDefaults(Notification.DEFAULT_VIBRATE) 
      .setPriority(Notification.PRIORITY_HIGH) 
      .setLights(0xff00ff00, 1000, 1000) 
      .setAutoCancel(true); 

    mNotificationManager.notify(0, mBuilder.build()); 
} 

Но когда я запускаю приложение, после 1 минуты отображается только уведомление о начале занятий. класс-конец notif должен был показывать 1 минуту после уведомления о начале занятий.

Начальный символ отображается так, как должно быть, то есть через каждую минуту. Но конец notif никогда не отображается, даже не один раз.

Если в методах testAlarmA() и testAlarmB() я вносил изменения, так что testAlarmB() запускается перед testAlarmA(), будет показан только B/end. A/start никогда не будет отображаться.

My Log

07-14 22:04:49.258 30137-30137/in.ac.iitd.bsw.iitdapp I/time: onReceive 
07-14 22:04:49.286 30137-30137/in.ac.iitd.bsw.iitdapp I/time: containsKey 
07-14 22:04:49.287 30137-30137/in.ac.iitd.bsw.iitdapp I/time: start 
07-14 22:06:29.165 30137-30137/in.ac.iitd.bsw.iitdapp I/time: onReceive 
07-14 22:06:29.173 30137-30137/in.ac.iitd.bsw.iitdapp I/time: containsKey 
07-14 22:06:29.173 30137-30137/in.ac.iitd.bsw.iitdapp I/time: start 
07-14 22:07:59.689 30137-30137/in.ac.iitd.bsw.iitdapp I/time: onReceive 
07-14 22:07:59.690 30137-30137/in.ac.iitd.bsw.iitdapp I/time: containsKey 
07-14 22:07:59.690 30137-30137/in.ac.iitd.bsw.iitdapp I/time: start 
07-14 22:09:52.756 30137-30143/in.ac.iitd.bsw.iitdapp W/art: Suspending all threads took: 5.590ms 
07-14 22:10:29.623 30137-30137/in.ac.iitd.bsw.iitdapp I/time: onReceive 
07-14 22:10:29.624 30137-30137/in.ac.iitd.bsw.iitdapp I/time: containsKey 
07-14 22:10:29.624 30137-30137/in.ac.iitd.bsw.iitdapp I/time: start 
07-14 22:11:59.696 30137-30137/in.ac.iitd.bsw.iitdapp I/time: onReceive 
07-14 22:11:59.696 30137-30137/in.ac.iitd.bsw.iitdapp I/time: containsKey 
07-14 22:11:59.696 30137-30137/in.ac.iitd.bsw.iitdapp I/time: start 
07-14 22:13:23.618 30137-30137/in.ac.iitd.bsw.iitdapp I/time: onReceive 
07-14 22:13:23.618 30137-30137/in.ac.iitd.bsw.iitdapp I/time: containsKey 
07-14 22:13:23.657 30137-30137/in.ac.iitd.bsw.iitdapp I/time: start 
07-14 22:15:43.136 30137-30137/in.ac.iitd.bsw.iitdapp I/time: onReceive 
07-14 22:15:43.136 30137-30137/in.ac.iitd.bsw.iitdapp I/time: containsKey 
07-14 22:15:43.136 30137-30137/in.ac.iitd.bsw.iitdapp I/time: start 

ответ

0

В testAlarmA и testAlarmB метод вы используете Intent конструктор, который действие установки, нет необходимости повторного вызова SetAction. И в методе setAction вы передаете Long.toString (System.currentTimeMillis()), который, я думаю, вы вставили по ошибке, попробуйте удалить это.

посмотреть пристальный конструктор: https://developer.android.com/reference/android/content/Intent.html#Intent(java.lang.String)

и метод SetAction: https://developer.android.com/reference/android/content/Intent.html#setAction(java.lang.String)

+0

Я использовал 'Long.toString (System.currentTimeMillis())' в 'setAction()', потому что я прочитал в stackOverflow, что каждое намерение должно иметь разный уникальный идентификатор setAction ID, а так как системное время всегда будет уникальным для каждое действие, таким образом, я использовал это. –

+0

Я также пробовал без 'setAction()', все тот же результат. Спасибо за ответ –

0

Привет При создании объекта pendingIntent убедитесь, что каждая цель имеет различные уведомления ID, как показано ниже

PendingIntent deletePendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), notificationId, deleteIntent, 0); 

где notificationId это когда открытое приложение вам нужно пройти один, и после запуска вам нужно будет еще один

+0

Да, я знаю об этом, и, как вы можете видеть, у меня есть разные идентификаторы для каждого ожидающего намерения, то есть 111 и 222 для первого и второго соответственно. 'PendingIntent широковещательный = PendingIntent.getBroadcast (getContext(), 111, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);' ' PendingIntent широковещательный = PendingIntent.getBroadcast (getContext(), 222, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);' Спасибо за ответ. –