我使用Android NotificationCompat.Builder,每次用户打开或关闭应用程序时,它都会发送后台通知。
我想知道应该写些什么,以便该通知通常只显示一次。这意味着如果用户一旦收到此通知或从其屏幕删除了该通知,就不会再显示此通知?
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
context, channelID)
.setSmallIcon(icon)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.icon))
.setColor(ContextCompat.getColor(context, R.color.white))
.setContentTitle("") .setContentText(getResources().getString(R.string.message))
.setLights(Color.RED, 3000, 3000)
.setVibrate(new long[]{0, 1000})
.setSound(null)
.setAutoCancel(true);
mBuilder.setPriority(Notification.PRIORITY_MIN);
Notification notification = mBuilder.build();
if (Build.VERSION.SDK_INT >= 26) {
startForeground(id, notification);
stopForeground( false );
notificationManager.cancel(id);
}
答案 0 :(得分:0)
使用带有SharedPreferences的标志来检查您是否已经发送了通知。如果已发送,则可以将标志更新为1。下次,如果标志值为1,则跳过发送通知。
SharedPreferences preferences = getApplicationContext().getSharedPreferences("app", 0);
int notificationFlag = preferences.getInt("notification", 0);
if (notificationFlag == 0) {
// The notification is not yet sent.
// Send the notification first and mark the flag as 1
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("notification", 1)
} else {
// The Notification is already sent once.
}