I'm programming some Android App that must make some Notification/Alarm after event occurs. Im wondering is there any function for NotificationManager like requireInteraction()?
Now when the certain event occurs the app just shows one notification for 1 sec, that's it..i'd like user to click OK to stop this vibration/sound
I found some code for notification from here:
NotificationCompat.Builder deprecated in Android O
Thanks #Mehul
public void showNotification (String from, String notification,
Intent intent) {
int requestID = (int) System.currentTimeMillis();
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
requestID,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
Notification mNotification = builder
.setContentTitle(from)
.setContentText(notification)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.build();
notificationManager.notify(/*notification id*/requestID, mNotification);
}
This one shows notification and it doesnt wait for user Input
If there is a need to add the buttons or action after clicking on notification you can use in your builder:
To add an button:
.addAction(new NotificationCompat.Action(*icon*, "Title", *intent for notification*));
or to add action that happen after user click the notification
.setContentIntent(*intent*);
Check the documentation about tab action and actions if you need more details.
Related
I am using this to show notifications:
public static void showAlarmNotification(Context context, Class<?> cls, String title, String content, int idNotification){
Intent notificationIntent = new Intent(context, cls);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(cls);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(idNotification, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID).setPriority(NotificationCompat.PRIORITY_MAX);
Notification notification = builder.setContentTitle(title)
.setContentText(content)
.setAutoCancel(false)
.setOngoing(true)
.setVibrate(new long[] {1000, 1000, 1000})
.setSmallIcon(R.drawable.ic_stat_name)
.setChannelId(NOTIFICATION_CHANNEL_ID)
.setContentIntent(pendingIntent)
.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID_ALARM, context.getString(R.string.alarms), NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setSound(null,null);
notificationChannel.setVibrationPattern(new long[] {1000, 1000, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(idNotification, notification);
}
It works fine to display a notification. But I want the notification not to disappear automatically as it normally happens, I want it to only go up if the user swipes it up, I have seen applications doing that but I have not found a way to do it
UPDATE
This example shows a notification that is not hidden until the user swipes it up
Example (YouTube)
That appears to be a notification with a set category of CATEGORY_ALARM.
See also system-wide category
The solution is to change setContentIntent to setFullScreenIntent, this is the source
I am trying to create a notification for Incoming call. For that I have added two actions in notification. My action text only is displayed.Action icon is not displayed in notification.
I want to add icon near Answer and cancel which I added as AddAction in Notification. I have added action icon like below,
NotificationCompat.Action answerAction = new NotificationCompat.Action.Builder(R.drawable.answer_call_icon, "Answer", pendingIntent).build();
NotificationCompat.Action cancelAction = new NotificationCompat.Action.Builder(R.drawable.cancel, "Cancel", pendingIntent).build();
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setLargeIcon((BitmapFactory.decodeResource(getResources(), R.drawable.call_logo)))
.setContentTitle(intent.getStringExtra("Number"))
.setSmallIcon(R.drawable.call_logo)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setFullScreenIntent(pendingIntent, true)
.setCategory(NotificationCompat.CATEGORY_CALL)
.addAction(answerAction)
.addAction(cancelAction)
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManagerCompat nManager = NotificationManagerCompat.from(this);
nManager.notify(2,builder.build());
One more query,
Below is my notification channnel,
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_HIGH);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.FLAG_FOREGROUND_SERVICE);
chan.setImportance(NotificationManager.IMPORTANCE_HIGH);
chan.setSound(defaultRingToneUri,audioAttributes);
chan.enableLights(true);
chan.shouldShowLights();
chan.setVibrationPattern(vibrate);
chan.enableVibration(true);
Context context=getApplicationContext();
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
Not able to get ringtone while receiving notification. Is the way Im setting sound is right??
Anybody please help me to solve this...
Posted 2 days ago..but till now not able to find solution.
As per the Notifications in Android N blog post:
Notification actions have also received a redesign and are now in a visually separate bar below the notification.
You’ll note that the icons are not present in the new notifications; instead more room is provided for the labels themselves in the constrained space of the notification shade. However, the notification action icons are still required and continue to be used on older versions of Android and on devices such as Android Wear.
So it is expected that you do not see the icons associated with notification actions.
If you need more flexibility in creating the notification layout, go for the custom one.
Ref: https://developer.android.com/training/notify-user/custom-notification
Use the Drawable left/right option to set an icon with text in the button.
// Get the layouts to use in the custom notification
RemoteViews notificationLayout = new RemoteViews(getPackageName(), R.layout.notification_small);
RemoteViews notificationLayoutExpanded = new RemoteViews(getPackageName(), R.layout.notification_large);
// Apply the layouts to the notification
Notification customNotification = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(notificationLayout)
.setCustomBigContentView(notificationLayoutExpanded)
.build();
As I understand: you have a problem with your notification you can use this method :
private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.addLine(message);
Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.setSound(alarmSound)
.setStyle(inboxStyle)
.setWhen(getTimeMilliSec(timeStamp))
.setContentText(message)
.build();
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Constant.NOTIFICATION_ID, notification);
}
or this one :
private void showBigNotification(Bitmap bitmap, NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
bigPictureStyle.setBigContentTitle(title);
bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
bigPictureStyle.bigPicture(bitmap);
Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.setSound(alarmSound)
.setStyle(bigPictureStyle)
.setWhen(getTimeMilliSec(timeStamp))
.setContentText(message)
.build();
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Constant.NOTIFICATION_ID_BIG_IMAGE, notification);
}
To play ringtone you can make use of android mediaplayer as shown below:
Var _mediaPlayer = MediaPlayer.Create(this,
Android.Provider.Settings.System.DefaultRingtoneUri);
_mediaPlayer.Start();
Task.Delay(60 * 1000).ContinueWith(t => _mediaPlayer?.Stop()); //stop after 60sec
You can take the global instance of _mediaPlayer and stop this as per user interaction with notification.
This is the c# xamarin android example, you can use the same class with java syntax.
I have the same issue as this person: NotificationManager Error Android Studio
However I already have the solution implemented a while ago but this just stopped working. I am at build API 28 on a P10 with Oreo 8.0.0 installed. My code executes the notification logic, but I get this error:
E/NotificationManager: notifyAsUser: tag=null, id=-1522221101, user=UserHandle{0}
and even though the icon for the notification pops up in the phone's notification bar, and tapping it opens my intent, the user gets no notification that this message arrived. I tried with the app in the foreground and in the background - both cases the small icon appears in the notification bar on top of the phone's UI, but no sound and no message.
Here is my code:
Intent intent = new Intent(getContext(), AuthRequestActivity.class);
intent.putExtra(getContext().getPackageName().concat(".param0"), code);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel("default", "My Channel", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("ALP Push Notifications");
notificationManager.createNotificationChannel(channel);
}
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext(), "default").setSmallIcon(R.drawable.app_icon)
.setContentTitle("Authentication Request").setContentText(code)
.setAutoCancel(true).setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getContext());
// Below alternative makes no difference
// NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int) System.currentTimeMillis(), notificationBuilder.build());
What am I doing wrong?
I need the code of Android notification with timing when notification was received.
I was testing notification in my app with following code
public void onPageFinished(WebView view, String url) {
Log.d("App Loaded ==", "Do");
NotificationManager notif=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notify=new Notification.Builder
(getApplicationContext()).setContentTitle("testing").setContentText("This is testing").
setContentTitle("time notification").setSmallIcon(R.drawable.ic_notification).build();
notify.flags |= Notification.FLAG_AUTO_CANCEL;
notif.notify(0, notify);
}
Kindly suggest why this is not working on page finished event. No notification is being triggered.
You have to check android version from where you are testing the app.
if its Oreo+ then you have to add notification channel, otherwise you will not get notification.
and please replace the Notification class with NotificationCompat as its deprecated.
try with this code you will surely get notification.
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, id)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(artist)
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCustomContentView(contentView)
.setColor(ctx.getResources().getColor(R.color.colorPrimary))
.setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE);
if (notificationManager != null) {
notification =builder.build();
notificationManager.notify(1, builder.build());
}
and if you want to log time while notification coming, you can add 1 line of code inside the Onreceived : Log.d(TAG, "Time: "+System.currentTimeMillis());
I'am using FCM for getting new notification which I am able to show without any problem but when i open the app all my notification disappeared
this my code for creating new notification
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
mContext,mContext.getString(R.string.default_notification_channel_id));
Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.setStyle(inboxStyle)
.setWhen(getTimeMilliSec(timeStamp))
.setSmallIcon(R.drawable.notification_icon)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setContentText(message)
.build();
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
CharSequence name = "my_channel";
String Description = "This is my channel";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(mContext.getString(R.string.default_notification_channel_id), name, importance);
mChannel.setDescription(Description);
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mChannel.setShowBadge(false);
notificationManager.createNotificationChannel(mChannel);
}
int id = (int) System.currentTimeMillis();
notificationManager.notify(id, notification);
when click on a notification it opens an activity with extra data in
my intent
Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
resultIntent.putExtra("message", "wwwwwwww");
resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
mContext,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
now when i click on any notification it opens MainActivity with some extra value on which Main activity depends.
But when i click on a notification and it launches the activity all other notification disappeared.So, how can i prevent that and hide only clicked notification so user can see other notification
not quite sure whether it'll work or not but can u please try with setting the request code unique rather than 0.
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
replace 0 with the following
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,(int) System.currentTimeMillis(),intent,PendingIntent.FLAG_UPDATE_CURRENT);
try this
**.setPriority(NotificationManager.IMPORTANCE_HIGH)**
Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.setSound(alarmSound)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setWhen(getTimeMilliSec(timeStamp))
.setSmallIcon(ICON)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setContentText(message)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationManager.IMPORTANCE_HIGH)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(num, notification);