Im trying to show notifications from firebase messaging it works on oreo and above but only plays a sound on kitkat devices (I haven't got other devices or emulators to test against) and I get some strange error logs such as
Could not find class 'android.app.Notification$Action$Builder', referenced
from method android.support.v4.app.NotificationCompatBuilder.addAction
I'm really struggling to pin point this so here is the main of the code
private void sendNotification(Map<String, String> data) {
String author = data.get("USER_NAME");
String title = data.get("TITLE");
String body = data.get("BODY");
String id = data.get("USER_NUMBER");
String message = data.get("MESSAGE");
String type = data.get("TYPE");
String image = data.get("IMAGE");
String profileImage = data.get("USER_IMAGE");
String shortMessage = "";
Intent intent;
Bitmap bitmap;
Bitmap bitmap2;
intent = new Intent(this, MessageListActivity.class);
if (MessageListActivity.isAppRunning)
intent = new Intent(this, MainActivity.class);
intent.putExtra(Constants.USER_NAME, author);
intent.putExtra(Constants.USER_NUMBER, id);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
/*
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(intent);
*/
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
/*
String replyLabel = getString(R.string.notif_action_reply);
RemoteInput remoteInput = new RemoteInput.Builder(KEY_REPLY)
.setLabel(replyLabel)
.build();
*/
// If the message is longer than the max number of characters we want in our
// notification, truncate it and add the unicode character for ellipsis
if (message.length() > NOTIFICATION_MAX_CHARACTERS) {
shortMessage = message.substring(0, NOTIFICATION_MAX_CHARACTERS) + "\u2026";
}
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
if (type.equals("IMAGE")) {
bitmap = getBitmapfromUrl(image);
bitmap2 = getBitmapfromUrl(profileImage);
notificationBuilder
.setLargeIcon(bitmap2)
.setSmallIcon(R.drawable.message_me)
.setContentTitle(String.format(getString(R.string.notification_message), author))
.setStyle(new NotificationCompat.BigPictureStyle()
.setSummaryText(shortMessage)
.bigPicture(bitmap))
.setContentText(message)
.setColor(getResources().getColor(R.color.colorPrimary))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
} else if (type.equals("TEXT")) {
bitmap2 = getBitmapfromUrl(profileImage);
notificationBuilder
.setSmallIcon(R.drawable.message_me)
.setLargeIcon(bitmap2)
.setContentTitle(String.format(getString(R.string.notification_message), author))
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message))
.setContentText(shortMessage)
.setColor(getResources().getColor(R.color.colorPrimary))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
&& Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
notificationBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
getManager().notify(0 /* ID of notification */, notificationBuilder.build());
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationBuilder = getChannelNotification(title, body, shortMessage, SINGLE_CHANNEL_ID, pendingIntent, type, image, profileImage);
getManager().notify(0, notificationBuilder.build());
}
}
private NotificationManager getManager() {
if (mManager == null) {
mManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
}
return mManager;
}
all data is present and correct the first error I get from this is
Could not find class 'android.app.NotificationChannel', referenced from
method com.sealstudios.aimessage.MyFirebaseMessagingService.createChannels
and my createChannels method is this
#RequiresApi(api = Build.VERSION_CODES.O)
public void createChannels() {
// create single channel
NotificationChannel singleChannel = new NotificationChannel(SINGLE_CHANNEL_ID,
SINGLE_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
singleChannel.enableLights(true);
singleChannel.enableVibration(true);
singleChannel.setLightColor(R.color.colorPrimary);
singleChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
getManager().createNotificationChannel(singleChannel);
// create group channel
NotificationChannel groupChannel = new NotificationChannel(GROUP_CHANNEL_ID,
GROUP_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
groupChannel.enableLights(true);
groupChannel.enableVibration(true);
groupChannel.setLightColor(R.color.colorPrimary);
groupChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
getManager().createNotificationChannel(groupChannel);
}
but this is only called from onMessageReceived in an if bracket like this
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Check if message contains a data payload.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannels();
}
if (remoteMessage.getData().size() > 0) {
Map<String, String> data = remoteMessage.getData();
if (data.size() > 0) {
if (!(chatActive && remoteMessage.getData().get("USER_NAME").equals(senderID))) {
//TODO add a mute notifications
sendNotification(data);
}
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
}
}
as mentioned I get the full notification without any worries on android oreo from a seperate method which is this
#RequiresApi(api = Build.VERSION_CODES.O)
public NotificationCompat.Builder getChannelNotification(String title,
String body, String smallMessage, String channelId,
PendingIntent pendingIntent, String type, String largeImage,
String smallImage) {
if (type.equals("TEXT")) {
Bitmap smallBitmap = getBitmapfromUrl(smallImage);
return new NotificationCompat.Builder(getApplicationContext())
.setChannelId(channelId)
.setContentTitle(title)
.setStyle(new NotificationCompat.BigTextStyle().bigText(body))
.setContentText(body)
.setColor(getResources().getColor(R.color.colorPrimary))
.setSmallIcon(R.drawable.message_me)
.setLargeIcon(smallBitmap)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
} else if (type.equals("IMAGE")) {
Bitmap smallBitmap = getBitmapfromUrl(smallImage);
Bitmap largeBitmap = getBitmapfromUrl(largeImage);
return new NotificationCompat.Builder(getApplicationContext())
.setChannelId(channelId)
.setContentTitle(title)
.setStyle(new NotificationCompat.BigPictureStyle().setSummaryText(smallMessage).bigPicture(largeBitmap))
.setContentText(body)
.setColor(getResources().getColor(R.color.colorPrimary))
.setSmallIcon(R.drawable.message_me)
.setLargeIcon(smallBitmap)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
}
return new NotificationCompat.Builder(getApplicationContext())
.setChannelId(channelId)
.setContentTitle(title)
.setContentText(body)
.setColor(getResources().getColor(R.color.colorPrimary))
.setSmallIcon(R.drawable.message_me)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
}
but otherwise i just get a notification sound, I'm sure it used to work before i raised my target sdk to 27 but any help would be appreciated
this looks like it was fixed by updating gradle plugins
Related
I'm working in a xamarin forms app, and I'm trying to develop an Android notification with two buttons:
In the first one you can write text, and this text must be retrieve to one of the ViewModels.
The second one should open a view of the app.
I have no experience with intents nor Android, and so far I can show the notification with the two buttons:
notification example
The class in charge of showing the notification is LocalNotifications : ILocalNotifications class in the Android solution:
class LocalNotifications : ILocalNotifications
{
const string channelId = "default";
const string channelName = "Default";
const string channelDescription = "The default channel for notifications.";
...
bool channelInitialized = false;
int messageId = 0;
int replyPendingIntentId = 0;
int photoPendingIntentId = 0;
NotificationManager manager;
public event EventHandler NotificationReceived;
public static LocalNotifications Instance { get; private set; }
public LocalNotifications() => Initialize();
public void Initialize()
{
if (Instance == null)
{
CreateNotificationChannel();
Instance = this;
}
}
public void SendNotification(string title, string message)
{
if (!channelInitialized)
{
CreateNotificationChannel();
}
Show(title, message);
}
public void ReceiveNotification(string title, string message)
{
var args = new NotificationEventArgs()
{
Title = title,
Message = message,
};
NotificationReceived?.Invoke(null, args);
}
private static readonly string KEY_TEXT_REPLY = "key_text_reply";
AndroidX.Core.App.RemoteInput remoteEntryInput = new AndroidX.Core.App.RemoteInput.Builder(KEY_TEXT_REPLY)
.SetLabel("Escribir entrada")
.Build();
private Intent replyIntent;
private Intent photoIntent;
public void Show(string title, string message)
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(AndroidApp.Context, channelId)
.SetContentTitle(title)
.SetContentText(message)
.SetLargeIcon(BitmapFactory.DecodeResource(AndroidApp.Context.Resources, Resource.Drawable.abc_ab_share_pack_mtrl_alpha))
.SetSmallIcon(Resource.Drawable.abc_ab_share_pack_mtrl_alpha)
.SetDefaults((int)NotificationDefaults.Sound | (int)NotificationDefaults.Vibrate);
NotificationCompat.Action reply = CreateReplyIntent(title, message);
builder.AddAction(reply);
NotificationCompat.Action image = CreateImageIntent();
builder.AddAction(image);
Notification notification = builder.Build();
manager.Notify(messageId++, notification);
}
NotificationCompat.Action CreateReplyIntent(string title, string message)
{
//replyIntent = new Intent(AndroidApp.Context, typeof(MainActivity));
replyIntent = new Intent();
replyIntent.PutExtra(TitleKey, title);
replyIntent.PutExtra(MessageKey, message);
// Build a PendingIntent for the reply action to trigger.
PendingIntent replyPendingIntent =
PendingIntent.GetBroadcast(AndroidApp.Context, replyPendingIntentId++, replyIntent, PendingIntentFlags.UpdateCurrent);
// Create the reply action and add the remote input.
return new NotificationCompat.Action.Builder(Resource.Drawable.abc_ab_share_pack_mtrl_alpha,
"Escribir entrada", replyPendingIntent)
.AddRemoteInput(remoteEntryInput)
.Build();
}
NotificationCompat.Action CreateImageIntent()
{
//photoIntent = new Intent("android.media.action.IMAGE_CAPTURE");
photoIntent = new Intent(AndroidApp.Context, typeof(MainActivity));
//photoIntent.SetFlags( ActivityFlags.LaunchAdjacent | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Build a PendingIntent for the reply action to trigger.
PendingIntent phtoPendingIntent = PendingIntent.GetBroadcast(AndroidApp.Context, photoPendingIntentId++, photoIntent, PendingIntentFlags.UpdateCurrent);
return new NotificationCompat.Action.Builder(Resource.Drawable.abc_ab_share_pack_mtrl_alpha,
"Sacar foto", phtoPendingIntent)
.Build();
}
void CreateNotificationChannel()
{
manager = (NotificationManager)AndroidApp.Context.GetSystemService(AndroidApp.NotificationService);
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
var channelNameJava = new Java.Lang.String(channelName);
var channel = new NotificationChannel(channelId, channelNameJava, NotificationImportance.Default)
{
Description = channelDescription
};
manager.CreateNotificationChannel(channel);
}
channelInitialized = true;
}
}
Which a don't get is how/where the app can react to those PendintIntents and how to pass the information from the android solution to the xamarin forms model.
Hi I have a push notification handler in my Android project. My goal is to have a different payload for each notification.
The problem is when I received notifications
and tap on a notification I want, the payload I get is usually the very first notification arrived. So for example from my screenshot, I tapped on notification with qHzkeyRp~~~~~: 2 I get the payload from Jayson Pogi: 1 notification. Other scenario is when I tapped on the first notification arrived, other notifications doesn't have payload.
Here's my code just incase
public void CreateLocalNotificaiton(string title, string body, string payload, int notifId, string groupName, bool hasIntent = false)
{
//var notificationBuilder = new NotificationCompat.Builder(this, AppConstants.NotificationChannelName)
// .SetContentTitle(title)
// .SetSmallIcon(Resource.Drawable.appicon)
// .SetContentText(body)
// .SetPriority(1)
// .SetVisibility((int)NotificationVisibility.Public)
// .SetChannelId(AppConstants.NotificationChannelId)
// .SetAutoCancel(true)
// .SetGroup("com.pordiva.omnigoo.businessmobile.OmniGoo")
// .SetShowWhen(false)
// ;
var notificationBuilder = new NotificationCompat.Builder(this, AppConstants.NotificationChannelName)
.SetContentTitle(title)
.SetSmallIcon(Resource.Drawable.appicon)
.SetContentText(body)
.SetPriority(PRIORITY_DEFAULT)
.SetChannelId(AppConstants.NotificationChannelId)
.SetAutoCancel(true)
//.SetGroupSummary(true)
//.SetGroup("com.pordiva.omnigoo.businessmobile." + groupName)
;
if (hasIntent)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.NewTask | ActivityFlags.SingleTop);
// add extra data so we can retreive this
if (payload != null)
{
Bundle bundle = new Bundle();
bundle.PutString("payload", payload);
intent.PutExtras(bundle);
}
var pendingIntent = PendingIntent.GetActivity(
this,
0,
intent,
PendingIntentFlags.OneShot);
notificationBuilder.SetContentIntent(pendingIntent);
}
var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager; // NotificationManager.FromContext(CrossCurrentActivity.Current.AppContext);
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
NotificationImportance importance = global::Android.App.NotificationImportance.High;
NotificationChannel notificationChannel = new NotificationChannel(AppConstants.NotificationChannelId, title, importance);
notificationChannel.EnableLights(true);
notificationChannel.EnableVibration(true);
notificationChannel.SetShowBadge(true);
notificationChannel.Importance = NotificationImportance.High;
notificationChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });
if (notificationManager != null)
{
notificationBuilder.SetChannelId(AppConstants.NotificationChannelId);
notificationManager.CreateNotificationChannel(notificationChannel);
}
}
notificationManager.Notify(notifId, notificationBuilder.Build());
}
SOLVED
Must have unique value in PendingIntent.GetActivity requestCode parameter
SOLVED ✌💪
Must have unique value in PendingIntent.GetActivity requestCode parameter
I have push notifications with custom sounds working until android 10. Since Android 11 the sound attached to the notification channel stopped playing when the notification is presented as drop down style. It works when it is presented as full screen activity.
Here is the example source code how the notification channel is created
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "media_playback_channel_v_01_1_sound"
String channelName = "Channel High"
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("My custom sound");
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
AudioAttributes.Builder builder = new AudioAttributes.Builder();
builder.setUsage(AudioAttributes.USAGE_NOTIFICATION);
String basePath = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/" + R.raw.alarm_sound);
Uri alarmSound = Uri.parse(basePath);
channel.setSound(alarmSound, builder.build());
channel.enableVibration(true);
channel.enableLights(true);
channel.setLightColor(Color.RED);
}
}
I use the notification channel above and fire the notification as follow:
private void fireNotification(Context context) {
String channelId = "media_playback_channel_v_01_1_sound"
NotificationChannel channel = getManager().getNotificationChannel(channelId);
PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(context, 100,
fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);
String contentText = getString(R.string.call_notification_incoming_from, from);
Bundle args = new Bundle();
args.putInt(CallActivity.INTENT_CALL_NOTIFICATION_ID, ActiveCall.ANDROID_10_PUSH_CALL_NTFN_ID);
args.putBoolean(CallActivity.INTENT_FROM_CALL_NOTIFICATION, true);
args.putString(CallActivity.INTENT_NOTIFICATION_CALL_ID, fullScreenIntent.getStringExtra(CallActivity.INTENT_NOTIFICATION_CALL_ID));
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, type)
.setSmallIcon(iconRes)
.setContentTitle(getString(R.string.app_name))
.setContentText(contentText)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOngoing(true)
.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_ALL)
.setTimeoutAfter(Consts.MINUTE)
.addExtras(args);
notificationBuilder.addAction(
R.drawable.ic_accept_call,
getString(R.string.call_notification_incoming_answer),
answerPendingIntent);
notificationBuilder.addAction(
R.drawable.ic_decline_bttn,
getString(R.string.call_notification_incoming_reject),
rejectPendingIntent
);
notificationBuilder.setFullScreenIntent(fullScreenPendingIntent, true);
// Build
Notification notification = notificationBuilder.build();
notification.sound = notificationSoundUri;
notification.flags |= (Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_INSISTENT Notification.FLAG_NO_CLEAR);
notification.ledARGB = Color.RED;
notification.ledOnMS = 300;
notification.ledOffMS = 1000;
// Notify
NotificationManager notificationManager = getManager();
notificationManager.notify(id, notification);
}
Note that the same code plays the sound in Android 10, while it does not on Android 11.
I am also stuck for android 11 but I tried different channel name and do not channel channel ID.
This solution is working for me in every android version 11 devices.
Please try this and let me know if this will not working for you.
public void showNotification(String title, String message) {
count++;
Intent intent = new Intent(this, HomePageActivity.class);
String channel_id = "notification_channel";
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getApplicationContext().getPackageName() + "/" + R.raw.coin);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), channel_id)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setAutoCancel(true)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setOnlyAlertOnce(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
builder.setNumber(count);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
builder = builder.setContent(getCustomDesign(title, message));
} else {
builder = builder.setContentTitle(title).setContentText(message).setSmallIcon(R.mipmap.ic_launcher_round);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(channel_id, "DIFFRENT_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH); // Here I tried put different channel name.
notificationChannel.setShowBadge(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
notificationChannel.canBubble();
}
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
notificationChannel.canShowBadge();
notificationChannel.enableVibration(true);
notificationChannel.setSound(soundUri, audioAttributes);
notificationManager.createNotificationChannel(notificationChannel);
notificationManager.notify(0, builder.build());
}
}
Finally, after researching a lot, I found a solution. All you need is this:-
While Creating Notification Channel, create different channels for Silent Notification, Custom Sound Notification, etc.
// The custom sound file name you want
val soundName = "beep"
val soundUri = Uri.parse("${ContentResolver.SCHEME_ANDROID_RESOURCE}://${packageName}/raw/${soundName}")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val importance = NotificationManager.IMPORTANCE_HIGH
val audioAttributes = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build()
// Here The CHANNEL_ID is the main thing for creating a channel. Use this same CHANNEL_ID in Notification Builder Also.
val channel = NotificationChannel(CHANNEL_ID, getString(R.string.app_name), importance).apply {
description = getString(R.string.app_name)
setSound(null, audioAttributes) // Give Null if you want silent notification
// setSound(soundUri, audioAttributes)
}
notificationManager.createNotificationChannel(channel)
}
Notification Builder:-
// Here The CHANNEL_ID needs to be same like the above created channel id. Because it defines how notification sound come.
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(smallIcon)
with(notificationManager) {
notify(notificationId, builder.build())
}
I am using this code to show notification in my android Application. This is working fine in all android version but no notification is showing in Android 9.
I tried to implement this with different method but nothing worked.
public void showNotification(String heading, String description, String imageUrl, Intent intent){
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
createChannel();
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,"channelID")
.setSmallIcon(R.drawable.logo)
.setContentTitle(heading)
.setContentText(description)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
notificationManager.notify(notificationId, notificationBuilder.build());
}
public void createChannel(){
if (Build.VERSION.SDK_INT < 26) {
return;
}
NotificationManager notificationManager =
(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel("channelID","name", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("Description");
notificationManager.createNotificationChannel(channel);
}
Thanks..
Hi this is very Late Answer but I still want to mark the mistake in the code as well as the working code snippet so that It can help others.
you are having two instance of notificationManager on in the showNotification(..) function and another in the createChannel() function. You must create channel in the same instance of the notificationManager so your working code will be like:
public void showNotification(String heading, String description, String imageUrl, Intent intent){
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,"channelID")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle(heading)
.setContentText(description)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
createChannel(notificationManager);
notificationManager.notify(notificationId, notificationBuilder.build());
}
public void createChannel(NotificationManager notificationManager){
if (Build.VERSION.SDK_INT < 26) {
return;
}
NotificationChannel channel = new NotificationChannel("channelID","name", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("Description");
notificationManager.createNotificationChannel(channel);
}
Call Like:
showNotification("Heading","Description","",new Intent(this,MainActivity.class));
The Results:
how to get Notification with out using google cloud . i thought of running a thread in back ground service and update the Notification but how i can i do it.pls help me out thanks in advance
public class BackgroundThread implements Runnable {
#Override
public void run() {
List<InvoiceDetail> invoiceDetails = JsonReader.getInvoice();
if (invoiceDetails.size() > 0) {
NotificationManager nfman = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int notifyID = 1;
NotificationCompat.Builder builder = new NotificationCompat.Builder(
LoginActivity.this).setContentTitle("WORK ASSIGNED")
.setContentText("You've received new messages.");
builder.setContentText("hai");
nfman.notify(1, builder.build());
}
}
}
public class Notifier extends BroadcastReceiver {
#SuppressWarnings("deprecation")
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sPrefs = context.getSharedPreferences("loginData", 0);
String id = sPrefs.getString("id", "default value");
String userss = sPrefs.getString("user", "default value");
String pass = sPrefs.getString("pass", "default value");
if (id.trim().length() > 0) {
List<NotifierDetail> subjects = DataBase.notificationMethod(id);
if (subjects.size() > 0) {
User user = new User();
user.setUserName(userss);
user.setPassWord(pass);
User users = DataBase.login(user);
BaseConstants.user = users;
for (NotifierDetail sub : subjects) {
NotificationManager nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(
R.drawable.logo, " Notification Today",
System.currentTimeMillis());
notification.defaults=Notification.DEFAULT_SOUND;
notification.defaults=Notification.DEFAULT_VIBRATE;
DataBase.updateNotificationMethod(sub.getId());
notification.flags = Notification.FLAG_AUTO_CANCEL;
Intent in = new Intent(context, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(context, 0,
in, 0);
CharSequence name = "Notification";
CharSequence mess = name + " about " + sub.getSubject();
notification.setLatestEventInfo(context, name, mess, pi);
nm.notify(0, notification);
}
}
}
}
}