5

Когда мое приложение запущено, он выполняет вызов API, а затем рассылает уведомления на основе результатов. Это составляет около 10 уведомлений, которые планируются. Кажется, что проблема связана с тем, что временная метка, отображаемая в фактическом уведомлении, является неправильной.Неправильная метка времени для будущих уведомлений

Поскольку я создаю эти уведомления, а затем планирую будильник с AlarmManager, время по умолчанию, указанное в уведомлении, будет временем, в которое создается уведомление (System.currentTimeMillis()).

Я попытался использовать метод .setWhen() на своем Notification.Builder, чтобы установить его в то время, которое я использую, чтобы запланировать ранее упомянутый сигнал. Это немного лучше, однако, поскольку уведомления не гарантируются в указанное время, я часто получаю уведомления за несколько минут в прошлом.

Кроме того, я попытался вручную переопределить when поле на уведомления в моей BroadcastReceiver, прямо перед .notify() на самом деле называется:

public class NotificationPublisher extends BroadcastReceiver { 

    public static String NOTIFICATION_ID = "notification_id"; 
    public static String NOTIFICATION = "notification"; 

    public void onReceive(Context context, Intent intent) { 

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

     Notification notification = intent.getParcelableExtra(NOTIFICATION); 
     notification.when = System.currentTimeMillis(); 
     int id = intent.getIntExtra(NOTIFICATION_ID, 0); 
     notificationManager.notify(id, notification); 

    } 
} 

Однако в описанном выше сценарии, кажется, что .when игнорируется.

Честно говоря, я просто ищу способ отображения временной отметки в уведомлении временем ее фактического отображения.

ответ

2

Я бы предложил передать информацию вашего уведомления как дополнительные, а затем создать уведомление внутри BroadcastReceiver. Это приведет к созданию уведомления непосредственно перед его выпуском, поэтому он будет иметь то же самое время, когда AlarmManager запускает BroadcastReceiver.

где бы вы планирования уведомления:

private void scheduleNotification(){ 

    // Create an intent to the broadcast receiver you will send the notification from 
    Intent notificationIntent = new Intent(this, SendNotification.class); 

    // Pass your extra information in 
    notificationIntent.putExtra("notification_extra", "any extra information to pass in"); 

    int requestCode = 1; 

    // Create a pending intent to handle the broadcast intent 
    PendingIntent alarmIntent = PendingIntent 
       .getBroadcast(this, requestCode, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

    // Set your notification's trigger time 
    Calendar alarmStart = Calendar.getInstance(); 
    alarmStart.setTimeInMillis(System.currentTimeMillis()); 
    alarmStart.set(Calendar.HOUR_OF_DAY, 6); // This example is set to approximately 6am 

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 

    // Set the alarm with the pending intent 
    // be sure to use set, setExact, setRepeating, & setInexactRepeating 
    // as well as RTC_WAKEUP, ELAPSED_REALTIME_WAKEUP, etc. 
    // where appropriate 
    alarmManager.set(AlarmManager.RTC_WAKEUP, alarmStart.getTimeInMillis(), alarmIntent); 
} 

Затем внутри вашего BroadcastReceiver в OnReceive:

String notificationExtra = null; 

// Retrieve your extra data 
if(intent.hasExtra("notification_extra")){ 
    notificationExtra = intent.getStringExtra("notification_extra"); 
} 

//Build the notification 
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context); 
mBuilder.setSmallIcon(notificationIcon) 
     .setContentTitle(notificationTitle) 
     .setContentText(notificationMessage) 
     .setAutoCancel(true); // Use AutoCancel true to dismiss the notification when selected 

// Check if notificationExtra has a value 
if(notificationExtra != null){ 
    // Use the value to build onto the notification 
} 

//Define the notification's action 
Intent resultIntent = new Intent(context, MainActivity.class); // This example opens MainActivity when clicked 

int requestCode = 0; 

PendingIntent resultPendingIntent = 
     PendingIntent.getActivity(
       context, 
       requestCode, 
       resultIntent, 
       PendingIntent.FLAG_UPDATE_CURRENT 
     ); 

//Set notification's click behavior 
mBuilder.setContentIntent(resultPendingIntent); 

// Sets an ID for the notification 
int mNotificationId = 1; 

// Gets an instance of the NotificationManager service 
NotificationManager mNotifyMgr = 
     (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 

// Builds the notification and issues it. 
mNotifyMgr.notify(mNotificationId, mBuilder.build()); 
+0

спасибо @sammy позвольте мне попробовать это! – xbadal

+0

Спасибо, сэм! работал Прекрасно – xbadal

+0

Можете ли вы рассказать мне, как создать несколько уведомлений.? это можно сделать, предоставив mNotificationId? то мне нужно отменить то же самое! – xbadal

0

onReceive() метод вашего NotificationPublisher будет invoked только тогда, когда планируется alarm триггеров, как указано time. Когда вы создаете уведомление из метода onReceive(), оно обязательно покажет текущее время. Нет необходимости требовать использования метода .when или .setWhen().

Попробуйте это:

public class NotificationPublisher extends BroadcastReceiver { 

    public static String NOTIFICATION_ID = "notification_id"; 
    public static String NOTIFICATION = "notification"; 

    public void onReceive(Context context, Intent intent) { 

     int id = intent.getIntExtra(NOTIFICATION_ID, 0); 

     // Notification 
     Notification notification = new Notification.Builder(context)  
      .setContentTitle("This is notification title") 
      .setContentText("This is notification text") 
      .setSmallIcon(R.mipmap.ic_launcher).build(); 

     notification.flags |= Notification.FLAG_AUTO_CANCEL; 

     // Notification Manager 
     NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 

     notificationManager .notify(id, notification); 
    } 
} 

Если вы хотите перенаправить к activity, когда нажмите на Notification, то вы можете использовать PendingIntent и установить его на Notification.

public class NotificationPublisher extends BroadcastReceiver { 

    public static String NOTIFICATION_ID = "notification_id"; 
    public static String NOTIFICATION = "notification"; 

    public void onReceive(Context context, Intent intent) { 

     int id = intent.getIntExtra(NOTIFICATION_ID, 0); 

     Intent intent = new Intent(context, YourTargetActivity.class); 
     intent.putExtra("KEY_ID", id); // Pass extra values if needed 

     PendingIntent pI = PendingIntent.getActivity(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

     // Notification 
     Notification notification = new Notification.Builder(context)  
      .setContentTitle("This is notification title") 
      .setContentText("This is notification text") 
      .setSmallIcon(R.mipmap.ic_launcher) 
      .setContentIntent(pI).build(); 

     notification.flags |= Notification.FLAG_AUTO_CANCEL; 

     // Notification Manager 
     NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 

     notificationManager .notify(id, notification); 
    } 
} 

Надеется, что это поможет ~

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