push notification in android code example
Example 1: create notification android
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(yourContext.getApplicationContext(), "notify_001");
Intent ii = new Intent(yourContext.getApplicationContext(), YourMainActivty.class);
PendingIntent pendingIntent = PendingIntent.getActivity(yourContext, 0, ii, 0);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(notificationsTextDetailMode);
bigText.setBigContentTitle(notificationTitleDetailMode);
bigText.setSummaryText(usuallyAppVersionOrNumberOfNotifications);
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle(notificationTitle);
mBuilder.setContentText(notificationText);
mBuilder.setPriority(Notification.PRIORITY_MAX);
mBuilder.setStyle(bigText);
NotificationManager mNotificationManager = (NotificationManager) yourContext.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel("notify_001",
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(channel);
}
if (mNotificationManager != null) {
mNotificationManager.notify(0, mBuilder.build());
}
Example 2: android foreground push notification
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d("msg", "onMessageReceived: " + remoteMessage.getData().get("message"));
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = "Default";
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody()).setAutoCancel(true).setContentIntent(pendingIntent);;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
manager.notify(0, builder.build());
}
}