我试图通过我的服务向我的用户显示通知,该服务会检查我的数据库当项目处于设置日期时应该发送通知。我的问题是,当日期到来时,它不会发送通知。
databaseReference = FirebaseDatabase.getInstance().getReference().child("Groups").child(mGroupUid).child("HomeFragment").child("FreezerItems");
childEventListener = databaseReference.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
HashMap<String, String> value = (HashMap<String, String>) dataSnapshot.getValue();
if (value != null) {
String name = value.get("Name");
String date = value.get("Date");
SimpleDateFormat sdf = new SimpleDateFormat("M/dd/yyyy", Locale.US);
try {
dateFormat = sdf.parse(date);
} catch (ParseException e) {
Log.wtf("FailedtoChangeDate", "Fail");
}
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, 1);
Date tomorrow = cal.getTime();
if (dateFormat.equals(tomorrow)) {
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
if (account != null) {
String firstname = account.getGivenName();
mContentTitle = "Your " + name + " is about to be expired!";
mContentText = firstname + ", make sure to cook or eat your " + name + " by " + date;
}
Intent openApp = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 100, openApp, PendingIntent.FLAG_UPDATE_CURRENT);
notification = new NotificationCompat.Builder(getApplicationContext(), "Default")
.setSmallIcon(R.drawable.ic_restaurant_black_24dp)
.setContentTitle(mContentTitle)
.setContentText(mContentText)
.setLights(Color.GREEN, 2000, 1000)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setStyle(new NotificationCompat.BigTextStyle().bigText(mContentText))
.setContentIntent(contentIntent)
.setAutoCancel(true);
createNotificationChannel(getApplicationContext());
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());
notificationManager.notify(uniqueID, notification.build());
}
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
我确定我的通知有效,因为当我删除if (dateFormat.equals(tomorrow))
时,它会发送通知并且完美无缺。这也是一个服务类而不是正常活动,所以可能与它有关。
答案 0 :(得分:0)
每个服务都有自己的上下文,只需使用它即可。按getApplicationContext()
更改YourServiceClass.this
。
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(YourServiceClass.this);
if (account != null) {
String firstname = account.getGivenName();
mContentTitle = "Your " + name + " is about to be expired!";
mContentText = firstname + ", make sure to cook or eat your " + name + " by " + date;
}
答案 1 :(得分:0)
dateFormat和明天都是Date()的对象,它们永远不会彼此相等。这就是为什么不满足条件并且没有发送通知的原因。 Instaed你可以尝试这个,
if(dateFormat.getTime() == tomorrow.getTime()) {
// Send notification
}