2017-08-04 35 views
-3

我有一個應用程序,我必須將每個通知接收的時間存儲在sharedpreference.I搜索了很多,但沒有找到任何解決方案。請讓我知道是否有任何可能性來做這種類型的問題。如何檢測收到通知的時間?

代碼: -

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()); 

} 
+0

你如何發送通知,在這裏發佈代碼。 –

+1

那麼問題是什麼?將你的時間存儲在你的通知接收者類中。 –

+0

我不知道如何存儲 – Niraj

回答

0

當你調用此方法通知會在狀態欄上張貼所以在這種方法保存樣的時間如下

SharedPreference sharePref=sharedPreferences = context.getSharedPreferences("notification_time", Context.MODE_PRIVATE); 
    SharedPreferences.Editor editor = sharePref.edit(); 
    edit.putLong("time_"+title,System.currentTimeMills()); 
    edit.apply(); 
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, ""); 
+0

以及如何區分當前日期和時間以及保存在Shred偏好中的日期和時間 – Niraj

+0

請檢查更新的答案 – Kharda