您可以通过多种方式构建本地通知。对于您的情况,我将建议最简单的方法。只需在将数据添加到 RecyclerView 之前立即调用buildLocalNotification()函数,然后通知在 RecyclerView 中更改的数据。
private void buildLocalNotification(String title,String message) {
Intent intent = new Intent(getApplicationContext(),BaseActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),0 /* Request code */,intent,PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this,channelId)
.setSmallIcon(R.drawable.ic_push_notification)
.setSound(defaultSoundUri)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
/**
* Since Android Oreo
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel(channelId,notificationManager);
}
assert notificationManager != null;
notificationManager.notify((int) System.currentTimeMillis(),notificationBuilder.build());
}
@SuppressLint("NewApi")
public void createNotificationChannel(String channelId,NotificationManager notificationManager) {
@SuppressLint("WrongConstant")
NotificationChannel channel = new NotificationChannel(channelId,getString(R.string.app_name),NotificationManager.IMPORTANCE_MAX);
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build();
assert notificationManager != null;
if (AppConstants.DEFAULT_NOTIFICATION_SOUND_URI != null) {
channel.setSound(AppConstants.DEFAULT_NOTIFICATION_SOUND_URI,att);
}
channel.setLightColor(Color.parseColor("#F1E605"));
channel.setVibrationPattern(VIBRATE_PATTERN);
channel.canShowBadge();
channel.enableVibration(true);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
本文链接:https://www.f2er.com/3154088.html