Status bar notification plugin error with Cordova - android

I'm trying to add the Status Bar Notification Plugin for Cordova to my Android App, but I get an error with it's code.
Here's the problematic code:
Notification noti = new Notification.Builder(context)
.setContentTitle(contentTitle)
.setContentText(contentText)
.setSmallIcon(icon)
.build();
The error is on the .build(), Eclipse tells me:
"The method build() is undefined for the type Notification.Builder"

I am having the same issue. It looks like a mismatch the sdk versions and now depreciated methods.
getNotification() is the method to call since API 11
build() was added in API 16
if you are like me, you are using a version < 16, so use .getNotification() instead.
Im not going to worry about API 16 right now but I bet if I download 16 and set my target to such, build() will work.
Let me know if it works for you.

For me .getNotification() didn't resolve the problem, because I need a solution for API 10 and higher.
I found a way to deal with it. If someone else has the same issue, I recommend to do this :
1) Go through instructions for StatusBarNotification (click)
2) Modify StatusBarNotification.java
Add
private Notification noti;
private PendingIntent contentIntent;
At the bottom of StatusBarNotification class, for example before NotificationManager declaration
Modify showNotification method
Comment or delete:
import android.app.Notification.Builder;
and
Notification noti = new Notification.Builder(context)
.setContentTitle(contentTitle)
.setContentText(contentText)
.setSmallIcon(icon)
.build();
Instead of this part, paste:
noti = new Notification(android.R.drawable.btn_star_big_on, contentText, System.currentTimeMillis() );
noti.flags = Notification.FLAG_AUTO_CANCEL;
Intent notificationIntent = new Intent(context, !yourMainActivityClass!.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent = notificationIntent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
noti.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
Change !yourMainActivityClass! to your class
Add calling method in index.html For tests you can make JQM button with
onclick='window.plugins.statusBarNotification.notify("Put your title
here", "Put your message here");return false;'
I know that this solution is using depreciated methods, but I spent a lof of hours to make it works and I didn't see another solution for API 10. If somebody has better idea, share with me ;)

Related

Android Notification Not working on Android 6.0 (Marshmallow)

I'm implementing local notification on Android and I have the problem that they are not appearing on Android 6.0 (Samsung S7).
I was searching for solutions, but I coulnd't find anything for this problem. I have the icon in the proper res/drawable folder, also I have defined a notification title, text, ringtone (raw folder) but it's not showing up...
There is my code:
Context acontext = getApplicationContext();
PackageManager pm = acontext.getPackageManager();
Intent notificationIntent = pm.getLaunchIntentForPackage(acontext.getPackageName());
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(acontext, 0, notificationIntent, 0);
int notification_icon = acontext.getResources().getIdentifier("icon", "drawable", acontext.getPackageName());
int notificationID = 0;
// Build notification
Notification noti = new Notification.Builder(acontext)
.setContentTitle("Title")
.setContentText("Incoming text")
.setSmallIcon(notification_icon)
.setContentIntent(pendingIntent)
.setLights(Color.RED, 1, 1)
.build();
NotificationManager notificationManager = (NotificationManager) acontext.getSystemService(Context.NOTIFICATION_SERVICE);
// hide the notification after its selected
noti.sound = Uri.parse("android.resource://" + acontext.getPackageName() + "/raw/incoming");
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(notificationID, noti);
Did anyone else experience this problem? Any help would be appreciated. Thank you.
There are some changes in new notification. new NotificationCompat.Builder(this) is deprecated and need NotificationChannelfor android oreo above. You can try this solution.
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(mContext.getApplicationContext(), "notify_001");
Intent ii = new Intent(mContext.getApplicationContext(), RootActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, ii, 0);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(verseurl);
bigText.setBigContentTitle("Title");
bigText.setSummaryText("Text in detail");
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round);
mBuilder.setContentTitle("Your Title");
mBuilder.setContentText("Your text");
mBuilder.setPriority(Notification.PRIORITY_MAX);
mBuilder.setStyle(bigText);
NotificationManager mNotificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("notify_001",
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
mNotificationManager.createNotificationChannel(channel);
}
mNotificationManager.notify(0, mBuilder.build());
There are various layers involved in showing notifications in Android, Please first check if this works for other devices of same OS version. Normally these kind of issues are device specific not OS specific, Also check notification logs how to check notification logs in android ?
If issue is device specific, following can be handy tips:
Check notifications not blocked for your app by device settings.
Check power settings blocking non-priority notifications.
If there are notifications in logs but not showing up, there can be some issue with your internal OS settings/configs. (believe me Android is not very clean OS)
If you can, try factory resetting your device. (In my case this worked)
Google Play Services must be enabled in order to receive push notifications on your Android device. If Google Play Services are enabled and the general troubleshooting steps have not resolved the issue, it may be necessary to reset the app. To reset the app, go to Settings → Apps → PagerDuty and tap Clear Data.
For Android 6.0 and newer, make sure the app is set as a prioritized app in priority mode.
For Android 6.0 and newer, check to see if the app is being silenced by Doze mode.
Check the android version accordingly set the icon for > 6.0 and for other.For 6.0 version we need white background icon.
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
icon = R.mipmap.your_logo_for_Lolipop;
}else{
icon = R.drawable.your_logo_for_Kitkat ;
}

The method setColor(int) is undefined for the type NotificationCompat.Builder

I'm working on a simple project which sends push notifications.
I wanted to design my notification a bit by setting colors, icons etc.
According to Android Developer site, there's a method to NotficationCompat.Builder class called setColor and setCategory, but both give me a compilation error.
I've updated the android.support.v4.... to the latest one, any more ideas?
Thanks in advance
EDIT: Here's a code snippet of the issue:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setDefaults(defaults)
.setSmallIcon(R.drawable.icon)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.alert))
.setColor(Color.RED) // The error is here!!!
//.setCategory(Notification.CATEGORY_ALARM)
.setWhen(System.currentTimeMillis())
.setSubText("Tap here for more details")
.setContentTitle("Care#Home Alert")
.setTicker("Care#Home Alert")
.setContentIntent(contentIntent)
.setAutoCancel(true);
The exact error is copied to the question title.
Updated:
The issue is that the support library wasnt updated to the latest version.
setColor is only available in Lollipop so, you've to check OSVersion
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
Notification notification = new Notification.Builder(context)}else {
Notification notification = new Notification.Builder(context)
notification.setColor(your_color)
}

Android notification is not showing

I need a program that will add a notification on Android. And when someone clicks on the notification, it should lead them to my second activity.
I have established code. The notification should be working, but for some reason it is not working. The Notification isn't showing at all. I don't know what am I missing.
Code of those files:
Notification n = new Notification.Builder(this)
.setContentTitle("New mail from " + "test#gmail.com")
.setContentText("Subject")
.setContentIntent(pIntent).setAutoCancel(true)
.setStyle(new Notification.BigTextStyle().bigText(longText))
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Hide the notification after it's selected
notificationManager.notify(0, n);
The code won't work without an icon. So, add the setSmallIcon call to the builder chain like this for it to work:
.setSmallIcon(R.drawable.icon)
Android Oreo (8.0) and above
Android 8 introduced a new requirement of setting the channelId property by using a NotificationChannel.
NotificationManager mNotificationManager;
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(mContext.getApplicationContext(), "notify_001");
Intent ii = new Intent(mContext.getApplicationContext(), RootActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, ii, 0);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(verseurl);
bigText.setBigContentTitle("Today's Bible Verse");
bigText.setSummaryText("Text in detail");
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round);
mBuilder.setContentTitle("Your Title");
mBuilder.setContentText("Your text");
mBuilder.setPriority(Notification.PRIORITY_MAX);
mBuilder.setStyle(bigText);
mNotificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
// === Removed some obsoletes
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
String channelId = "Your_channel_id";
NotificationChannel channel = new NotificationChannel(
channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(channel);
mBuilder.setChannelId(channelId);
}
mNotificationManager.notify(0, mBuilder.build());
Actually the answer by ƒernando Valle doesn't seem to be correct. Then again, your question is overly vague because you fail to mention what is wrong or isn't working.
Looking at your code I am assuming the Notification simply isn't showing.
Your notification is not showing, because you didn't provide an icon. Even though the SDK documentation doesn't mention it being required, it is in fact very much so and your Notification will not show without one.
addAction is only available since 4.1. Prior to that you would use the PendingIntent to launch an Activity. You seem to specify a PendingIntent, so your problem lies elsewhere. Logically, one must conclude it's the missing icon.
You were missing the small icon.
I did the same mistake and the above step resolved it.
As per the official documentation:
A Notification object must contain the following:
A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()
On Android 8.0 (API level 26) and higher, a valid notification channel ID, set by setChannelId() or provided in the NotificationCompat.Builder constructor when creating a channel.
See http://developer.android.com/guide/topics/ui/notifiers/notifications.html
This tripped me up today, but I realized it was because on Android 9.0 (Pie), Do Not Disturb by default also hides all notifications, rather than just silencing them like in Android 8.1 (Oreo) and before. This doesn't apply to notifications.
I like having DND on for my development device, so going into the DND settings and changing the setting to simply silence the notifications (but not hide them) fixed it for me.
Creation of notification channels are compulsory for Android versions after Android 8.1 (Oreo) for making notifications visible. If notifications are not visible in your app for Oreo+ Androids, you need to call the following function when your app starts -
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) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name,
importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviours after this
NotificationManager notificationManager =
getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
You also need to change the build.gradle file, and add the used Android SDK version into it:
implementation 'com.android.support:appcompat-v7:28.0.0'
This worked like a charm in my case.
I think that you forget the
addAction(int icon, CharSequence title, PendingIntent intent)
Look here: Add Action
I had the same issue with my Android app. I was trying out notifications and found that notifications were showing on my Android emulator which ran a Android 7.0 (Nougat) system, whereas it wasn't running on my phone which had Android 8.1 (Oreo).
After reading the documentation, I found that Android had a feature called notification channel, without which notifications won't show up on Oreo devices. Below is the link to official Android documentation on notification channels.
Notifications Overview, Notification anatomy
Create and Manage Notification Channels
For me it was an issue with deviceToken. Please check if the receiver and sender device token is properly updated in your database or wherever you are accessing it to send notifications.
For instance, use the following to update the device token on app launch. Therefore it will be always updated properly.
// Device token for push notifications
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(
new OnSuccessListener<InstanceIdResult>() {
#Override
public void onSuccess(InstanceIdResult instanceIdResult) {
deviceToken = instanceIdResult.getToken();
// Insert device token into Firebase database
fbDbRefRoot.child("user_detail_profile").child(currentUserId).child("device_token")).setValue(deviceToken)
.addOnSuccessListener(
new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
}
});
I encountered a similar problem to yours and while searching for a solution I found these answers but they weren't as direct as I hoped they would be but it gives an Idea; Your notifications may not be showing because for versions >=8 notifications are done relatively differently there is a NotificationChannel which aids in managing notifications this helped me. Happy coding.
void Note(){
//Creating a notification channel
NotificationChannel channel=new NotificationChannel("channel1",
"hello",
NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
//Creating the notification object
NotificationCompat.Builder notification=new NotificationCompat.Builder(this,"channel1");
//notification.setAutoCancel(true);
notification.setContentTitle("Hi this is a notification");
notification.setContentText("Hello you");
notification.setSmallIcon(R.drawable.ic_launcher_foreground);
//make the notification manager to issue a notification on the notification's channel
manager.notify(121,notification.build());
}
Make sure your notificationId is unique. I couldn't figure out why my test pushes weren't showing up, but it's because the notification ids were generated based on the push content, and since I was pushing the same notification over and over again, the notification id remained the same.
Notifications may not be shown if you show the notifications rapidly one after the other or cancel an existing one, then right away show it again (e.g. to trigger a heads-up-notification to notify the user about a change in an ongoing notification). In these cases the system may decide to just block the notification when it feels they might become too overwhelming/spammy for the user.
Please note, that at least on stock Android (tested with 10) from the outside this behavior looks a bit random: it just sometimes happens and sometimes it doesn't. My guess is, there is a very short time threshold during which you are not allowed to send too many notifications. Calling NotificationManager.cancel() and then NotificationManager.notify() might then sometimes cause this behavior.
If you have the option, when updating a notification don't cancel it before, but just call NotificationManager.notify() with the updated notification. This doesn't seem to trigger the aforementioned blocking by the system.
If you are on version >= Android 8.1 (Oreo) while using a Notification channel, set its importance to high:
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
val pendingIntent = PendingIntent.getActivity(applicationContext, 0, Intent(), 0)
var notification = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
.setContentTitle("Title")
.setContentText("Text")
.setSmallIcon(R.drawable.icon)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.build()
val mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
mNotificationManager.notify(sameId, notification)

Notification setLights() Default Value?

I want to create a custom notification. So i want to change the lights and the tone.
I use the NotificationCompat.Builder for that.
Now i want to change the Lights via setLights();
Works fine. But i want set the default value of the onMS and offMS. I haven't find something about that.
Can anybody help me to find the default values?
Here is the documentation for that: http://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#setLights(int, int, int)
See the Android source for answer:
<!-- Default color for notification LED. -->
<color name="config_defaultNotificationColor">#ffffffff</color>
<!-- Default LED on time for notification LED in milliseconds. -->
<integer name="config_defaultNotificationLedOn">500</integer>
<!-- Default LED off time for notification LED in milliseconds. -->
<integer name="config_defaultNotificationLedOff">2000</integer>
However different ROMs might have different values for these. For example mine returns 5000 for config_defaultNotificationLedOff. So you might want to fetch them at runtime:
Resources resources = context.getResources(),
systemResources = Resources.getSystem();
notificationBuilder.setLights(
ContextCompat.getColor(context, systemResources
.getIdentifier("config_defaultNotificationColor", "color", "android")),
resources.getInteger(systemResources
.getIdentifier("config_defaultNotificationLedOn", "integer", "android")),
resources.getInteger(systemResources
.getIdentifier("config_defaultNotificationLedOff", "integer", "android")));
According to diff, these attributes are guaranteed to exist on Android 2.2+ (API level 8+).
#Aleks G
that do not help. I have the latest update from the compat libaray. But Eclipse say build() isn avalaible.
I dont no why. The docu says yes and you...
This is my current code:
NotificationCompat.Builder notify = new NotificationCompat.Builder(context);
notify.setLights(Color.parseColor(led), 5000, 5000);
notify.setAutoCancel(true);
notify.setSound(Uri.parse(tone));
notify.setSmallIcon(R.drawable.ic_stat_kw);
notify.setContentTitle("Ttiel");
notify.setContentText("Text");
Intent showIntent = new Intent(context, Activity_Login.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, showIntent, 0);
notify.setContentIntent(contentIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notify.getNotification());
runs perfectly. But not with the default onMS and offMS in setLights() :(
You should be able to do this with:
Notifictaion notf = new Notification.Builder(this).setXXX(...).....build();
notf.ledARGB = <your color>;
notf.ledOnMS = <your value>; //or skip this line to use default
notf.ledOffMS = <your value>; //or skip this line to use default
Basically, don't use setLights on the notification builder. Instead, build the notification first - then you have access to individual fields for the lights.
Update: this is the actual copy/paste from my sample project, which compiles and works fine on android 2.1 and uses blue colour for LED:
Notification notf = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setTicker("This is the sample notification")
.setSmallIcon(R.drawable.my_icon)
.build();
notf.ledARGB = 0xff0000ff;
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, notf);

Why does it say "deprecated" for a method when its the only one I can use for the selected API-level?

In my Android manifest, it says this:
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="16" />
but when I write this code, the getNotification at the end gets me warning saying that the method is "deprecated":
Notification myNotification = new Notification.Builder(appContext)
.setContentTitle("SIC")
.setContentText(tickerText)
.setWhen(when)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setContentIntent(contentIntent)
.getNotification(); // <-- warning here
Now, the problem is that for API-level 10, which is the minimum I am developing for, getNotification is the only one there is to use. The newer method called "build()" is for API-level 16.
So why am I getting the deprecated warning even though its the only one I can and should use? One might think that the warning/docs should adapt to the minSdkLevel, not the highets one...
So why am I getting the deprecated warning even though its the only one I can and should use?
Because your build target is API Level 16 or higher, where this method is deprecated.
One might think that the warning/docs should adapt to the minSdkLevel, not the highets one
In that case, one would be incorrect. Deprecation has nothing to do with minSdkVersion, any more than it would in standard Java outside of Android (where deprecation exists and minSdkVersion does not).
Moreover, you should be using the Android Support package's version of Notification.Builder (called NotificationCompat.Builder, since the native one does not exist in API Level 10, which your manifest indicates that you are trying to support. build() should exist on NotificationCompat.Builder and work on all your desired API levels.
If you wanted to do it the "technically correct" way, you'd do something like
Notification bldr = new Notification.Builder(appContext)
.setContentTitle("SIC")
.setContentText(tickerText)
.setWhen(when)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setContentIntent(contentIntent);
Notification notif;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
notif = bldr.getNotification()
} else {
notif = bldr.build();
}
And then annotate the method with TargetApi(16). This is how you generally approach these types of problems.
In your case, you should just use NotificationCompat.Builder instead in the compatibility package.
This is an example how to create a notification using NotificationCompat class, supported in all API´s
public static void createNotificacion(Context ctx) {
try {
int smallIcon = R.drawable.ic_launcher;
Bitmap largeIcon = BitmapFactory.decodeResource(ctx.getResources(),R.drawable.ic_launcher);
long when = System.currentTimeMillis();
CharSequence contentTitle = "Jorgesys";
CharSequence contentText = "Hello Stackoverflow!!!";
Intent notificationIntent = new Intent();
/*create new task for each notification with pending intent so we set Intent.FLAG_ACTIVITY_NEW_TASK */
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
/*get the system service that manage notification NotificationManager*/
NotificationManager notificationManager =(NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
/*build the notification*/
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ctx)
.setWhen(when)
.setContentText(contentText)
.setContentTitle(contentTitle)
.setSmallIcon(smallIcon)
.setAutoCancel(true)
.setTicker(contentTitle)
.setLargeIcon(largeIcon)
.setContentIntent(pendingIntent);
/*sending notification to system. Here we use unique id (when)for making different each notification
* if we use same id, then first notification replace by the last notification*/
notificationManager.notify((int) when, notificationBuilder.build());
} catch (Exception e) {
Log.e("Notification Exception", e.getMessage());
}
}
best thing to do is to use the compatability library and forget about this problem:
http://developer.android.com/guide/topics/ui/notifiers/notifications.html
this way , you can enjoy all of the latest features of the notifications ...
I believe the warning relates to the fact that you're building with a newer SDK (due to your targetSDKVersion being higher). So you're actually able to use the newer method, but you need to be careful when using it, since devices that are below the target API level but above the min API level will not work with the newer API. You can check the API level before using the newer calls though to use them safely.
For example, if you wanted to use an Android 4.1 method while your minSDK is 2.3, you could do:
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
// API Specific code here
}
In this case the warning doesn't matter. You can add a #SuppressWarnings("deprecation") to the class or method.

Categories

Resources