InterviewSolution
| 1. |
How I will display popup message to a user with toast or SnakeBar. Explain with code. |
|
Answer» Notification is kind of short message that is used to post from an application for giving information that some event has been HAPPENING if the application is still not running in the background. From the Oreo, a new concept has come NAME as Notification Chanel. This is using for GROUPING notification based on behavior. So before creating any notification we need to create Notification Chanel at the application level and need to provide its id in Manifest file. For creating any notification we need to create an object of NotificationCompact.Builder. We can define all the components of Notification like title, IMAGE,duration etc by calling setters on the builder object. We can note that we pass a string as parameter to the NotificationCompact.Builder constructor, this string is the Notification Channel ID which means that this notification will now be a part of that particular channel. ublic static final String NOTIFICATION_CHANNEL_ID = "channel_id"; //Notification Channel ID passed as a parameter here will be ignored for all the Android versions below 8.0 NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID); builder.setContentTitle("New message "); builder.setContentText("You have new message "); builder.setSmallIcon(R.drawable.icon); builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon)); Notification notification = builder.build();At last we need to call NotificationManager object.and we will display our notification using notify() method. NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this); notificationManagerCompat.notify(NOTIFICATION_ID, notification);For adding action in Notification we need to specify action. When user click on notification it will open an activity in your app that corresponds to the notification. To do so, we will specify a content intent defined with a PendingIntent object and pass it to setContentIntent(). Intent intent = new Intent(this, MessageDetail.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("New Message") .setContentText("Message come") .SETPRIORITY(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(pendingIntent) .setAutoCancel(true); |
|