Step1 : Build Notification with Reply intent and heads up notification
private void buildInlineReplyNotification() {
// Create an instance of RemoteInput.Builder that you can add to your notification action.
// This class's constructor accepts a string that the system uses as the key for the text input.
// Later, your handheld app uses that key to retrieve the text of the input.
RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY).setLabel(
getResources().getString(R.string.reply_label)).build();
// Attach the RemoteInput object to an action using addRemoteInput().
NotificationCompat.Action compatAction =
new NotificationCompat.Action.Builder(R.mipmap.ic_reply,
getResources().getString(R.string.reply), replyPendingIntent).addRemoteInput(
remoteInput).setAllowGeneratedReplies(true).build();
// Build the notification and add the action.
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.ic_notification)
.setContentTitle(
getResources().getString(R.string.notification_created) + mNotificationId)
.setContentText(getResources().getString(R.string.type_reply))
.setShowWhen(true)
.addAction(compatAction);
mBuilder.setPriority(Notification.PRIORITY_HIGH).setVibrate(new long[0]);
// Issue the notification.
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(mNotificationId, mBuilder.build());
}
Step2 : cancel after reply from notification
private void updateNotification(Context context, int notifyId) {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context).setSmallIcon(R.mipmap.ic_notification)
.setContentText(context.getString(R.string.message_sent));
notificationManager.cancel(notifyId);
}
Issues is not cancel notification by notificationManager.cancel(notifyId) but if i remove this mBuilder.setPriority(Notification.PRIORITY_HIGH).setVibrate(new long[0]); Than work perfect so, what is issue with priority in notification ?
Related
Am trying to create a notification that will notify user when alarm matures, am calling the Notification code in my OnCreate method, so i expect to see it when i launch my Activity but my code here seems to have a problem, any help to get the App to notify will greatly be appreciated...
Here is what i got so far
class SecondActivity : AppCompatActivity
{
static readonly int mid = 1000;
static readonly string CHANNEL_ID = "location_notification";
protected override void OnCreate(Bundle onSavedInstanceState){
//Notification code
NotificationChannel channel = null;
Intent intent=new Intent(this, typeof(SecondActivity));
//Construct TaskStack builder for pending intent
Android.App.TaskStackBuilder taskStackBuilder = Android.App.TaskStackBuilder.Create(this);
//Add intent to backstack
taskStackBuilder.AddNextIntentWithParentStack(intent);
//Construct pending intent to open desired activity
PendingIntent pendingIntent = taskStackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
//Enque notification to inform the user that the alarm has matured
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.SetSmallIcon(Resource.Drawable.abc_tab_indicator_mtrl_alpha)
.SetContentTitle("Alarm")
.SetContentIntent(pendingIntent);
.SetContentText("Alarm Time has matured");
NotificationManager notificationManager =
(NotificationManager)GetSystemService(Context.NotificationService);
notificationManager.Notify(mid, mBuilder.Build());
channel = notificationManager.GetNotificationChannel(channelName);
notificationManager.CreateNotificationChannel(channel);
}
}
What Am i doing wrong?, Thanks
am calling the Notification code in my OnCreate method
You could not call notification on OnCreate method directly. Generaly We will use button click event or another separated task event to call Notification.
Second, as SushiHangover's said, you need to CreateNotificationChannel before publish
local notification.
You can refer to Notification channels to add notification channel:
void CreateNotificationChannel()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}
var channelName = Resources.GetString(Resource.String.channel_name);
var channelDescription = GetString(Resource.String.channel_description);
var channel = new NotificationChannel(CHANNEL_ID, channelName, NotificationImportance.Default)
{
Description = channelDescription
};
var notificationManager = (NotificationManager) GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
And pulish notification:
// Instantiate the builder and set notification elements:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.SetContentTitle ("Sample Notification")
.SetContentText ("Hello World! This is my first notification!")
.SetSmallIcon (Resource.Drawable.ic_notification);
// Build the notification:
Notification notification = builder.Build();
// Get the notification manager:
NotificationManager notificationManager =
GetSystemService (Context.NotificationService) as NotificationManager;
// Publish the notification:
const int notificationId = 0;
notificationManager.Notify (notificationId, notification);
Note: The CHANNEL_ID should be the same both on creating channel and publishing notification. Generally, we will use the package name as the channel id.
The full sample code as follows:
private void Button_Click(object sender, EventArgs e)
{
// create notification channel
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}
var channelName = "Notify user";
var channelDescription = "first local notification";
var channel = new NotificationChannel("com.companyname.appandroidlistview", channelName, NotificationImportance.Default)
{
Description = channelDescription
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "com.companyname.appandroidlistview")
.SetContentTitle("Sample Notification")
.SetContentText("Hello World! This is my first notification!")
.SetSmallIcon(Resource.Drawable.icon);
// Build the notification:
Notification notification = builder.Build();
// Get the notification manager:
NotificationManager notificationManager =
GetSystemService(Context.NotificationService) as NotificationManager;
// Publish the notification:
const int notificationId = 0;
notificationManager.Notify(notificationId, notification);
}
You need to do a lot of things before your notification can work, Microsoft documentation provides a very easy way of doing that...
class SecondActivity : AppCompatActivity
{
//Declare notification ID and Channel ID In your class so you can use them from any method
static readonly int NOTIFICATION_ID = 1000;
static readonly string CHANNEL_ID = "location_notification";
protected override void OnCreate(Bundle savedInstanceState){
}
//Define the method you will use to call notification
}
void createNotificationChannel()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}
var name = Resources.GetString(Resource.String.channel_name);
var description = GetString(Resource.String.channel_description);
var channel = new NotificationChannel(CHANNEL_ID, name, NotificationImportance.Default)
{
Description = description
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
//Use a button to send the notification to the operating system
private void notifier(object sender, EventArgs e){
Intent intent=new Intent(this, typeof(SecondActivity));
//Construct TaskStack builder for pending intent
Android.App.TaskStackBuilder taskStackBuilder = Android.App.TaskStackBuilder.Create(this);
//Add intent to backstack
taskStackBuilder.AddNextIntentWithParentStack(intent);
//Construct pending intent to open desired activity
PendingIntent pendingIntent = taskStackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
//Enque notification to inform the user that the alarm has matured
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.SetSmallIcon(Resource.Drawable.abc_tab_indicator_mtrl_alpha)
.SetContentTitle("Alarm")
.SetContentText("Alarm Time has matured")
.SetShowWhen(false).SetContentIntent(pendingIntent);
NotificationManagerCompat notificationManager = NotificationManagerCompat.From(this);
notificationManager.Notify(NOTIFICATION_ID, mBuilder.Build());
}
}
}
If you follow the instructions on this page then your notification should show without so much hassle
https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/notifications/local-notifications-walkthrough
I'm currently working on a library with android support.
I'm being asked to notify user on foreground service start.
The notification must contain "ApplicationName" as title, and "ApplicationName is running" as text. The notification icon has to be the same as the launcher one.
The target API level is 26.
The notification did not work because the previous developper forgot to open the notification chanel. This is now fixed, we have the notification that pops correctly. And the label are matching expectation.
But now i'm questioning why the notification contains the expected values. I could not find any reference in the javadoc.
The following code will display the notification as expectecd the application's name as title and the text "ApplicationName is running" :
#Override
public void onCreate() {
NotificationChannel channel = new NotificationChannel("APPLICATION_CHANNEL", "MyService", NotificationManager.IMPORTANCE_LOW);
channel.setDescription(notificationChannelText);
//block below useful for head up notification
channel.setSound(null, null);
channel.setShowBadge(false);
channel.enableLights(false);
channel.enableVibration(false);
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
#Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
foregroundNotification();
return Service.START_STICKY;
}
/**
* In order to start foreground service we and generate a service running notification.
*/
private void foregroundNotification() {
Context context = getApplicationContext();
Intent notificationIntent = new Intent(context, getClass());
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = new Notification.Builder(context, "APPLICATION_CHANNEL")
.setContentTitle("Title")
.setContentText("Subject")
.setContentIntent(pendingIntent)
.build();
startForeground(42666, notification);
}
Why doesn't it just display a notification with "Title" as the title and "Subject" as content ?
Are there any constants or magic values that we have to know ?
Where can we find any documentation or definition about it ?
Edit 2020/04/01 : Added code representing notification channel creation
I found your problem. This is result of your code:
and after add small icon:
.setSmallIcon(R.mipmap.ic_launcher)
It works fine
I want to show every single notification separately and not repeat same notification which is already present on status bar in android.
Here is my code which is giving me multiple notification in one notification actually its updating current notification which I don't want.
private void showNotification(String message) {
Intent i = new Intent(this,NotificaitonDesign.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("message_send",message_send);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentTitle("Discount Location")
.setContentText(message)
.setSmallIcon(R.drawable.bell_notification)
.setSound(sound)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0,builder.build());
}
You need a unique id for each notification
manager.notify(unique_id, builder.build());
Also, you can cancel a specific notification using it's unique id
You can achieve this using this simple example for generating a 'run-time' static int that will be unique.
public class UniqueId {
private static int id = 0;
public static int nextId() {
return id = id++;
}
}
I have followed the Xamarin walkthrough, and it's not working for me.
The code falls through this cleanly, but it never sends the notification.
It never shows up on my emulator or device.
I have no idea what is going on.
public override void OnReceive(Context context, Intent intent)
{
string message = intent.GetStringExtra("message");
string title = intent.GetStringExtra("title");
int id = int.Parse(intent.GetStringExtra("id"));
//Generate a notification with just short text and small icon
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.SetAutoCancel(true) // Dismiss from the notif. area when clicked
.SetContentTitle(title) // Set its title
.SetContentText(message); // The message to display.
NotificationManager notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);
notificationManager.Notify(id, builder.Build());
Any help or links would be very helpful. I'm just completely lost; been working on this for about 14 hours now, and cannot find any help on the Google.
Answer to my inquiry: You must have an Icon set for notifications to be properly build and sent. Though, it won't send an error for not having one.
Short version: Needed to add
.SetSmallIcon(Resource.Drawable.icon);
Add an icon to notification.
Notification.Builder builder = new Notification.Builder (this)
.SetContentTitle ("Title")
.SetContentText ("Message")
.SetSmallIcon (Resource.Drawable.ic_notification);
Notification notification = builder.Build();
NotificationManager notificationManager =
GetSystemService (Context.NotificationService) as NotificationManager;
const int notificationId = 0;
notificationManager.Notify (notificationId, notification);
I am trying to modify existing notifications in android.
What I have in my app
When a notification is already in system tray and another notification appears, the second one overwrites the first notification content.
What I am looking for
If second Notification arrives then instead of overwriting the first I need to change title to show 2 New Messages and go on incrementing as notifications arrive.
Code Implemented
Bitmap icon = BitmapFactory.decodeResource(ctx.getResources(),
R.drawable.icon);
Intent launchActivity = new Intent(ctx, CordovaApp.class);
launchActivity.putExtra("heading",newsHeader);
launchActivity.putExtra("content",newsText);
PendingIntent pi = PendingIntent.getActivity(ctx,0, launchActivity, PendingIntent.FLAG_NO_CREATE);
ParseAnalytics.trackAppOpened(launchActivity);
if(pi==null){
Log.d(TAG, "Pending Intenet is null.");
}else{
Log.d(TAG, "Pending Intenet is not null.");
}
Notification noti = new NotificationCompat.Builder(ctx)
.setContentTitle(newsHeader)
.setContentText(newsText)
.setSmallIcon(R.drawable.icon)
.setLargeIcon(icon)
.setContentIntent(pi)
.setAutoCancel(true)
.build();
NotificationManager nm = (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(0, noti);
Update
I implemented the solution mentioned below by #yogendra and now I am getting two separate notifications. Instead of getting stacked. Below is updated code
Notification noti = new NotificationCompat.Builder(ctx)
.setContentTitle(newsHeader)
.setContentText(newsText)
.setSmallIcon(R.drawable.icon)
.setGroup(GROUP_KEY_EMAILS)
.setLargeIcon(icon)
.setContentIntent(pi)
.setLights(Color.parseColor("green"), 5000, 5000)
.setAutoCancel(true)
.setPriority(2)
.setTicker("Notification from App")
.setGroupSummary(true)
.build();
NotificationManager nm = (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE);
int timeSeconds = (int)System.currentTimeMillis()%Integer.MAX_VALUE;
Log.i(TAG,"Timing function called "+timeSeconds);
nm.notify(timeSeconds, noti);
See your code
nm.notify(0, noti);
where
notify(int id, Notification notification)
Here 0 is the ID of notification which is to be managed with respect to each notification. If you want to show a different notification your notification id should be unique each time. If you try to post a notification with the same notification id your previously displayed notification will be replaced with the latest notification.
Solution
Now you need to display a custom notification with a custom layout and update the counter each time .
Source code to create a Custom Notification.
create global variable in your class :
private int count = 0;
private ArrayList<String> notificationList = new ArrayList<String>();
private String GROUP_KEY_EMAILS = "email";
/call method createNotification when you need to create notification and pass message what you need to show on message./
private void createNotification(String notificationMassage) {
notificationList.add(notificationMassage);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
// Create builder
Builder summaryNotification = new NotificationCompat.Builder(this)
.setContentTitle(notificationList.size()+" new messages")
.setSmallIcon(R.drawable.settings)
.setLargeIcon(largeIcon)
.setGroup(GROUP_KEY_EMAILS)
.setGroupSummary(true)
.setAutoCancel(true);
// Create style
InboxStyle nStyle = new NotificationCompat.InboxStyle();
nStyle.setBigContentTitle(notificationList.size()+" new messages");
nStyle.setSummaryText("Summery Text...<you can set as blank>");
for (String Str : notificationList) {
nStyle.addLine(Str);
}
summaryNotification.setStyle(nStyle);
mNotificationManager.notify(0, summaryNotification.build());
count++;
}
/**
please clear notification array list after tap on notification.
*/
For more detail please refer below link:
https://developer.android.com/training/wearables/notifications/stacks.html#AddGroup
https://developer.android.com/training/wearables/notifications/stacks.html#AddGroup