B4A Library Custom Notification Library: Barx

Hello guys and girls.

Note: this library has been superceded by Notification Builder Library

Here is my first library. It allows you to create custom notifications and has more settings for the notifications than the b4a Notification Object.

Additional settings include:
  • Setting Ticker Text
  • Setting custom patterns for LED and Vibration
  • Setting custom Notification alert tone
  • Setting the color and size of text elements
  • Plus more...

You can create custom Layouts for the notifications (XML knowledge required) or use one of the built in Presets. These include a progress bar layout to use for thing like showing file download progress.

There is a bug in Android 4.0.3 that shows Custom Notifications with the wrong background color. See this post. and the link in the post
http://www.b4x.com/forum/libraries-developers-questions/16916-ics-notification-background-bug.html
I have created a set of layout files just for this version of Android that hard code the background colors to the stock theme. These are automatically loaded with this version is used and no action is required from you to set them. This seems to work well. If a better solution is found I will update accordingly.

Some screen shots of the library in action:

twotextplusimage.png

onetextplusimageplusprogress.png

Documentation
  • CustomNotification
    Permissions:
    • android.permission.VIBRATE
    Properties:
    • AlertOnce As
      Sets whether the notification sound and/or vibration should sound each time the notification is sent, even if it has not been cancelled before.
    • AutoCancel As
      Sets whether the notification will be cancelled automatically when the user click on it
    • DefaultLED As
      Sets whether the notification will Flash the LED (if available) using the Default settings.

      NOTE: Setting to True will over rule the CustomLED

      Example:
      n.DefaultLED = False
    • DefaultSound As
      Sets whether the notification will play a sound using the default settings
      Example:
      n.DefaultSound = True
    • DefaultVibrate As
      Sets whether the notification will vibrate using the default settings

      NOTE: Setting to True will overrule the CustomVibrate

      Example:
      n.DefaultVibrate = True
    • Insistent As
      Sets whether the sound will play repeatedly until the user opens the notification screen
    • NoClear As
      Sets whether the notification should NOT be cancelled when the user clicks the Clear All button.
      Example:

      Dim cn as CustomNotification

      cn.NoClear = True 'Notification will not clear.
    • Number As Int
      Gets or Sets a number that will be displayed over the icon. This is useful to represent multiple events in a single notification.
    • OnGoingEvent As
      Set if the notification is in reference to an ongoing event, e.g. a phone call.
      Do not set for notifications that are in reference to something that happened at a particular point in time.
    • TickerText As
      Sets the Ticker Text which shows along side the status bar icon on new notification.

      Example:
      cn.TickerText = "New notification"
    • When As Long
      <B>Note: Experimental Feature</B>
      The offical description of this method is - <i>The timestamp for the notification.</i>

      Setting this to the max Value for a long (9,223,372,036,854,775,807) pushes the Notification Icon to the right.
    Methods:
    • Cancel (Id As Int)
      Cancels the notification with the given Id
    • Initialize (Layout As Int)
      Initializes the notification setting default values of:
      LED = Enabled
      Sound = Enabled
      Vibration = Enabled
      Layout - Sets the layout to be used.
      Options:
      1 = Default notification layout (Two Text fields plus Icon)
      2 = Two Text fields plus One Image
      3 = One Text field plus One Image plus One Progress Bar
      4 = Two Text fields ONLY
      5 = User Defined. Add your xml file to the res/layout. Name it mylayout.xml and make it read only.

      Example:
      cn.Initialize(2) 'Initializes the notification and sets the layout to Two Text fields plus One Image
    • IsInitialized As Boolean
    • Notify (Id As Int)
      Displays the notification.
      Id: - The notification Id. This can be used later to update the notification (by calling notify again with the same Id) or cancel it.
    • SetCustomSound (path As String)
      Sets a custom sound to be played on new notification

      Example:
      cn.CustomSound("file:///sdcard/notification/ringer.mp3")
    • SetCustomVibrate (Values As Long())
      Sets A custom vibrate sequence for notification Vibration
      The Array of values can be as long as you wish.
      The First Value is the pause before vibration starts, then it's ON, OFF, ON, OFF, etc.

      NOTE: DefaultVibrate must be set to False

      Example:
      Dim cn as CustomNotification
      Dim v() as Long

      v = Array as Long(0, 100, 200, 300, 400)
      cn.DefaultVibrate = False
      cn.CustomVibrate(v)
    • SetImage (id As String, Image As Bitmap)
      Sets image used in a notification. Only use with "twotextsplusimage" and "onetextplusimageplusprogress" Presets or if defined as part of a user defined layout.
      For Preset layout the id is "image".
    • SetIntent (Activity As Object)
      Sets the Activity that is called when the user clicks the notification
      Example:
      cn.Activity(Main)
    • SetProgress (id As String, maxProgress As Int, progress As Int, indeterminate As Boolean)
      Sets the parameters for a progress bar used in a notification. Only use with "onetextplusprogress" Preset or if defined as part of a user defined layout.
      For Preset layout the id is "progress".

      maxProgress - the upper limit of the progress bar. A good value is 100
      progress - the current level of progress to be shown. Must be <= maxProgress.
    • SetTag (Tag As String)
      The Tag is a string that can be extracted later on Activity_Resume.
      This can be used to determine which notification has been clicked by the user when multiple notifications exist.

      Example of extracting the Tag:
      Sub Activity_Resume
      Dim in as Intent
      Dim intentExtra as String

      in = Activity.GetStartingIntent
      If in.HasExtra("Notification_Tag") Then
      intentExtra = in.GetExtra("Notification_Tag")
      End If
      End Sub
    • SetText (id As String, text As String)
      Sets the content of text items for the notification
      For Preset Layouts the id's are "title" and "text".
      Example:

      cn.SetText("title", "New notification")
      cn.SetText("text", "You have a new notification")
    • SetTextColor (id As String, Color As Int)
      Sets the Color of a text item.
      For Preset Layouts the id's are "title" and "text".
      Example:

      cn.SetText("title", "New notification")
      cn.SetTextColor("title", Colors.Red)
    • SetTextSize (id As String, Value As Int)
      Sets the text size of a text item.
      For Preset Layouts the id's are "title" and "text".
      Example:

      cn.SetText("title", "New notification")
      cn.SetTextSize("title", 20)
    • setCustomLED (LightOn As Int, LightOff As Int)
      Set a custom timing for the notification Light.
      Timings are in milliseconds.

      NOTE: DefaultLED must be set to False.

      Example:
      Dim cn as CustomNotification

      cn.DefaultLED = False
      cn.CustomLED(300, 1000)
    • setIcon (FileName As String)
      Sets the icon to be displayed.
      The image file should manually copied to the Objects\res\drawable\ folder and set to read-only.
      The file name is case sensitive and should not contain the file extension.
      You can use "icon" to use the applications icon.

      Example:
      cn.Icon("icon")


I hope you find this library useful and enjoy using it. If there are any problems, let me know and I will fix ASAP.

Thanks...

Credits:
Without the help of some members of the b4a community, this library would never been created. I want to give extra special thanks to:
NJDude who has help alot especially with testing and listened to me go on about notifications every day for about 3 weeks. He has also assured me he will add a sample project to show you all how easy this library is to use.
thedesolatesoul who has helped a huge amount and even beat me to a release.
corwin42 and warwound for their coding skills (of which I spent many hours reading) and many others have played a part.

Installation:
Please note:
this library requires your b4a installation to use v15 of the Android.jar see This Post for details.

This library uses 'res' files as well as the standard b4a library files.

Extract the CustomNotification.zip
Copy 'CustomNotification.jar' & 'CustomNotification.xml' to your b4a library folder.
Extract res.zip
Copy the 'res' folder to your projects 'Objects' folder and make all files copied withing the res folder 'Read-Only'. This is important!
Then just add the library as usual and code away.

Update - V1.10
Fixes a bug. When using layout(1) and setting Icon to something other than "icon". The notification still used "icon" for the image. Thanks to Inman

Update - V1.01
This is not a big update and doesn't add any functionality. Whilst using the library I noticed some errors in the tooltips so decided to correct them. An example being, in the DefaultLED tooltip the example was cn.Light instead of cn.DefaultLED. This could have led to some confusion.

Updated original link.

Thanks

Files attached below:
 

Attachments

  • res.zip
    47.4 KB · Views: 2,186
  • CustomNotification.zip
    7.7 KB · Views: 2,179
Last edited:

monki

Active Member
Licensed User
Longtime User
@barx @ NJDUDE

I have installed sdk 15 and it works fine.

Many Thank´s

monki
 

barx

Well-Known Member
Licensed User
Longtime User
@barx @ NJDUDE

I have installed sdk 15 and it works fine.

Many Thank´s

monki

Brilliant, thank you for letting us know.
 

bluedude

Well-Known Member
Licensed User
Longtime User
Not for your own layout

Clear,

So this one is not when you want to use your own layout, that's the other library called custom notifications :)
 

barx

Well-Known Member
Licensed User
Longtime User
Clear,

So this one is not when you want to use your own layout, that's the other library called custom notifications :)

You use this one ;)

I'm sorry for causing the confusion, this lib can do everything the 'other' one does plus a bit more. Also this doesn't require a separate notification object to be created first.
 

bluedude

Well-Known Member
Licensed User
Longtime User
Pretty confusing indeed

Indeed it is pretty confusing because I see two libraries and two authors.

So if I would add my own layout I should rename it to mylayout and initialize it by using number 5?

And then I should put it in both layout and layout-15 because of the ICS bug?

WebView isn't supported in notifications?

Cheers,
 

thedesolatesoul

Expert
Licensed User
Longtime User
Indeed it is pretty confusing because I see two libraries and two authors.

So if I would add my own layout I should rename it to mylayout and initialize it by using number 5?

And then I should put it in both layout and layout-15 because of the ICS bug?

WebView isn't supported in notifications?

Cheers,

Okay, I have depreciated my library :sign0148:. This one has more features.

No you cannot have a webview in notifications. Only certain views are supported in a remote view. (Buttons, Labels, Panels, ImageViews, Progresbars)
 

barx

Well-Known Member
Licensed User
Longtime User
Indeed it is pretty confusing because I see two libraries and two authors.

So if I would add my own layout I should rename it to mylayout and initialize it by using number 5?

And then I should put it in both layout and layout-15 because of the ICS bug?

WebView isn't supported in notifications?

Cheers,

Yes call it 'mylayout' and initialize using (5). OR if it is similar to one of the presets, just edit the preset.

The -v15 version of the layouts vary slightly so that things line up nicely on ICS. Also the background color is hard coded (until a fix id released or I find a better solution). So it's not a simple copy from one to other. If you compare the 'twotextplusimage' files in both folders you will get the idea. Any issues creating -v15 layouts lets me know and I'll ty to help.

Don't forget to clean project after tinkering with these res files.

See tds's reply about webview.
 

barx

Well-Known Member
Licensed User
Longtime User
Updated to v1.01. Edited original post with details...
 

Kevin

Well-Known Member
Licensed User
Longtime User
I'm getting around to experimenting with this after posting about my problems with the stock notifications on certain devices.

Unfortunately, I can't get this to work. :(

The code below vibrates twice (as set to do for my testing) but nothing shows up in the Notification tray. Worse, if I uncomment the line that sets the icon, it force closes my app. And there is definitely an icon named "icon.png" in the res\drawable folder. :)

Not sure what I am missing here. I tried using android-8 SDK as well as android-15 as mentioned earlier in this thread.

If it makes a difference, this sub is being called from an activity but the sub itself is in a code module.

B4X:
ToggleNotificationIcon2 (OnOff As Boolean)
  Dim n1 As CustomNotification
  Dim v() As Long
  v = Array As Long (0,150,50,150)
  n1.Initialize (1)
  n1.AlertOnce =  True
  n1.SetIntent (Main)
  n1.SetCustomVibrate (v)
  n1.DefaultVibrate = False
  n1.DefaultLED = False
  n1.DefaultSound = False   
  n1.OnGoingEvent = True
  n1.SetTextSize ("title",14)
  n1.SetTextSize ("text",12)
  'n1.setIcon ("icon")
 
 
  If OnOff = True Then
    n1.SetText ("title", "Test Title")
    n1.SetText ("text", "Test subtext")
    n1.Notify (1)
      Else
        Try
          n1.Cancel (1)
            Catch
        End Try
  End If
End Sub

:sign0085:
 
Last edited:

barx

Well-Known Member
Licensed User
Longtime User

barx

Well-Known Member
Licensed User
Longtime User
I'm getting around to experimenting with this after posting about my problems with the stock notifications on certain devices.

Unfortunately, I can't get this to work. :(

The code below vibrates twice (as set to do for my testing) but nothing shows up in the Notification tray. Worse, if I uncomment the line that sets the icon, it force closes my app. And there is definitely an icon named "icon.png" in the res\drawable folder. :)

Not sure what I am missing here. I tried using android-8 SDK as well as android-15 as mentioned earlier in this thread.

If it makes a difference, this sub is being called from an activity but the sub itself is in a code module.

B4X:
ToggleNotificationIcon2 (OnOff As Boolean)
  Dim n1 As CustomNotification
  Dim v() As Long
  v = Array As Long (0,150,50,150)
  n1.Initialize (1)
  n1.AlertOnce =  True
  n1.SetIntent (Main)
  n1.SetCustomVibrate (v)
  n1.DefaultVibrate = False
  n1.DefaultLED = False
  n1.DefaultSound = False   
  n1.OnGoingEvent = True
  n1.SetTextSize ("title",14)
  n1.SetTextSize ("text",12)
  'n1.setIcon ("icon")
 
 
  If OnOff = True Then
    n1.SetText ("title", "Test Title")
    n1.SetText ("text", "Test subtext")
    n1.Notify (1)
      Else
        Try
          n1.Cancel (1)
            Catch
        End Try
  End If
End Sub

:sign0085:

I'm just about to test your code Kevin any chance of a log?
 

barx

Well-Known Member
Licensed User
Longtime User
@kevin, your code seems to work fine. 3 things for you to try.

1) I'm sure it just got missed off the 'copy/paste' but your sub posted above is missing just that. The sub keyword at the beginning.

2) make sure you copied the 'res' folder to your projects folder and made the file read only as described in the installation instructions. If you have done this step, just double check the layout files are there in 'Objects/res/layout/'

3) whenever you manually add any resources to your project (i.e copying over the res folder in this case) be sure to clean your project. 'Tools', 'Clean Project'.

thanks for trying the lib and hope this gets it sorted for you. Any tips on improving the user experience are welcomed.
 

Kevin

Well-Known Member
Licensed User
Longtime User
Yes, the missing "Sub" was a pasting error... Had to fix the post several times, kept getting the weird html formatting codes when previewing. :)

Anyway, I'll try to post the error log later (didn't even think to look at that), but after reading the first post again, I think I am missing something. Either in my head or in the zip file with the library in post one. I see no "res" folder in the zip, so I accidentally missed that step during installation. Maybe it is because I just woke up, but I'm a bit confused now. :)

Update:
Can I get a copy of all of the missing res files? I saw the demo zip someone else posted but I don't know what he may have customized in it. I plan to just use the default style for now (no custom xml layouts for the notification). I assume I don't need to do anything special, and it will just work on all versions of Android? I am guessing I need to reference Android-15 SDK in order for it to work on newer Android versions, and that it will also work on all older ones? Sorry for the noob questions, but I don't want to break my notifications for a bunch of people in my effort to fix them for a few.
 
Last edited:

barx

Well-Known Member
Licensed User
Longtime User
Very sorry for that kevin. I forgot to add the res folder to the zip when I did the minor update. Not very pro of me.

I'm away from home for a good few hours but will get it added when I get back and reply so you know its done. Really sorry for the confusion and trouble.

Sent from my HTC Desire Z
 

Kevin

Well-Known Member
Licensed User
Longtime User
No big deal on the missing files. At least it wasn't me just doing something wrong in my code. Not that that ever happens. :D

I'll check in a bit later to see if you've updated the zip.

I assume that if I don't use any custom layouts that it will look exactly like the stock B4A notification? I don't want to upset the masses by changing its appearance. :rolleyes:
 

barx

Well-Known Member
Licensed User
Longtime User
OK, I have added the 'res' files as a separate zip to the original post so that in future I won't forget them ;)

Extract the res.zip
Copy the 'res' folder to your projects 'Objects' folder and make all files copied withing the res folder 'Read-Only'.

As you have done already, using layout '1' on the initialize uses a layout that mimics the standard notification.

Test it out and see if it looks exact enough, I think it is the same ;)
If it is not quite right, give me a shout and I'm sure we can sort it out.

The best way to test it would be to create a copy of your project and work on that one, then if it isn't to your liking, you simple go back to the old one.

hope this helps
 

Kevin

Well-Known Member
Licensed User
Longtime User
Got it working now, thanks!

It does look a bit different. The icon is bigger than standard and the fonts sizes are a bit different, along with no time at the right.

I was going to play with the jar file but as it is not plain text, I don't really have a clue. Is there an easy way for me to use the custom settings (sounds, vibration, etc) but use non-custom / stock layouts? In other words, specifiy the other options but not a layout?

From the SDK, it appears you are always specifying a layout (which obviously is a big part of your library, to use custom notifications) as mentioned in the quote below? I guess what I would like to do is just use the standard layout if possible?

By default, the notification that appears in the notifications window includes a title and the message text. These are defined by the contentTitle and contentText parameters of the setLatestEventInfo() method. However, you can also define a custom layout for the notification using RemoteViews. Figure 3 shows an example of a custom notification layout. It looks similar to the default notification, but is actually created with a custom XML layout.
To define your own layout for the notification, instantiate a RemoteViews object that inflates a custom layout file, then pass the RemoteViews to the contentView field of your Notification.

I really hate to sound so picky, but it does look a bit different from the others, at least on my phone.
 

Attachments

  • notification.jpg
    notification.jpg
    32 KB · Views: 354

barx

Well-Known Member
Licensed User
Longtime User
Ahh yes I can see the differences.

We have 2 options here. Either edit the layout files to try and make it match the default (Shouldn't be too hard) or I can have a go at a new library that will simply extend the standard notification object (So layout will be exact).

btw the layouts files are in res/layout/ and the file in use for you is 'twotextplusimage'. if you open it with notepad you will see the xml code. it may or may not make sense to you.

Let me know which way you wish to go and I'll try to get it complete this evening for you. UK Time.

NOTE: I will eventually do both these tasks but will do the one that suits you best first ;)
 

Kevin

Well-Known Member
Licensed User
Longtime User
I definitely don't want to create more work for you. I thought about trying to edit the XML but my concern there was that even if I get it to look right on my device, would it look right on all of the others.

If I knew how to do it, what I would want to do is just add the customizable vibration patterns, etc to the stock B4A notification object. That would allow me to keep them identical in appearance but also attempt to work around the device-specific vibration issues I am seeing.
 
Top