如何检测收到通知的时间?

时间:2017-08-04 09:16:56

标签: android notifications

我有一个应用程序,我必须将每个通知收到的时间存储在sharedpreference中。我搜索了很多但没有找到任何解决方案。如果有任何可能做这类问题,请告诉我。

代码: -

 public void customNotification(String title, String message,int image) {
    // Using RemoteViews to bind custom layouts into Notification
    RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.custom_notification_card);
    builder = new NotificationCompat.Builder(this);
    // BEGIN_INCLUDE(intent)
    //Create Intent to launch this Activity again if the notification is clicked.
    Intent i = new Intent(this, MainActivity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(this, 0, i,
            PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(intent);
            // Set Icon
    builder .setSmallIcon(R.drawable.snap);
            // Dismiss Notification
    builder .setAutoCancel(true);
    builder .setOngoing(true);
            // Set RemoteViews into Notification
    builder.setContentIntent(intent);
    builder.setContent(remoteViews);

    // Locate and set the Image into customnotificationtext.xml ImageViews
    remoteViews.setImageViewResource(R.id.imagenotileft,image);

    // Locate and set the Text into customnotificationtext.xml TextViews
    remoteViews.setTextViewText(R.id.title,title);
    remoteViews.setTextViewText(R.id.text,message);

    // Create Notification Manager
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    // Build Notification with Notification Manager
    notificationManager.notify(0, builder.build());

}

2 个答案:

答案 0 :(得分:0)

当您调用此方法时,通知将在状态栏中发布,因此在此方法中保存时间,如下所示

  SharedPreference sharePref=sharedPreferences = context.getSharedPreferences("notification_time", Context.MODE_PRIVATE);
  SharedPreferences.Editor editor = sharePref.edit();
  edit.putLong("time_"+title,System.currentTimeMills());
  edit.apply();

答案 1 :(得分:0)

将此代码添加到方法的底部。 花时间像:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateAndTime = sdf.format(new Date());

然后将其保存到sharedPreference:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();

//for the id
int id = preferences.getInt("notification_received_time_id",0);
id += 1;
editor.putInt("notification_received_time_id",id);

//for the value

editor.putString("notification_received_time",currentDateAndTime);
editor.apply();

访问它(从其他任何地方)调用此代码:

notification_received_time_id = 1; //whichever id you want

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String notificationReceivedTime = preferences.getString(notification_received_time_id, "");