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,176
  • CustomNotification.zip
    7.7 KB · Views: 2,161
Last edited:

barx

Well-Known Member
Licensed User
Longtime User
I understand where your coming from kevin. I'm not 100% sure myself if one layout would suit all so to speak. I know ICS if different and there is already a separate layout file for that (in the layout-v15 folder). I think all the earlier versions are the same.

Anyway, I will have a go at adding the extra bits to the existing shortly. One thing I noticed before when I tried such a thing is that the tooltips (the popup instructions as you type in the IDE if you didn't know) for existing feature don't get imported, but so long as you can live with that for now, I'm sure i can get it up and running pretty quick.
 

Kevin

Well-Known Member
Licensed User
Longtime User
I could live without the tooltips. I'm not sure exactly how the library works internally. Would it be as simple as adding a new property such as .UseCustomLayout where if set to false it would just set the component up with no specific layout when the notification is set? I assume this would then mimic the stock B4A object, but of course it would also have the full set of options.

An alternative would be if Erel is interested in adding fuller functionality to his implementation of it, but I'm sure he has much bigger priorities. :)
 

barx

Well-Known Member
Licensed User
Longtime User
Ok Kevin here we go.

Please Find attached the start of the 'Advanced Notification' library. My first intention was to extend the existing which meant less code but for technical reasons isn't yet do able. So, (and I hope Erel doesn't mind) I have copied the full code for the standard notification object and then added the modifications to it to add the following features.

  • Ticker Text
  • Custom Vibration Pattern
  • No Clear

I have given it a quick test and it seems good. Basically, once you have installed this library, if you go back to your project that used the standard notification change

B4X:
Dim xxxxx as Notification

to

B4X:
Dim xxxxx as AdvancedNotification

Your existing settings will work fine and the new options will become available.

As mentioned above the existing options tool tips will be missing. I will add these when I get a bit more time and then release this as a library.

Installation

Download and extract the attached .zip file. Copy the 2 files to your libraries folder and add as usual

Note: This library does not require the 'res' files as it uses the built in layout.

Hope this helps.
 

Attachments

  • AdvancedNotification.zip
    4.2 KB · Views: 328

barx

Well-Known Member
Licensed User
Longtime User
An alternative would be if Erel is interested in adding fuller functionality to his implementation of it, but I'm sure he has much bigger priorities. :)

To be honest kevin I don't know why these features are missing in the b4a object. It isn't much extra code, maybe these features weren't available at the time, or maybe Erel thought the features may confuse people? only he knows the answer to that one. Maybe he wanted to give us a teaser but leave little bits out to get people doing things like this and building libraries to enhance the product.
 

Kevin

Well-Known Member
Licensed User
Longtime User
Thanks! To quote Google after installing the Chrome browser.... You're awesome!

It is working great as expected.

Out of curiosity just so I am clear on how it works, are the following the same?

B4A object (and your new library):

B4X:
n.Light = False:n.Sound = False:n.Vibrate = False

Your original custom library:

B4X:
an.DefaultLED = False:an.DefaultSound = False:an.DefaultVibrate = False

The reason I ask is because with the built-in B4A object, I had assumed that Light, Sound and Vibrate when set to True meant that they should always be on (and always off when False). But the options in your original custom library, though somewhat sounding like the exact same thing, imply that they are not necessarily always on or off, but rather it depends on how the device is set up for default notification options.

My only reason for asking is because I still do not understand why the Droid Charge seems to override the options I set in my app with the phone's options.

I already asked the last customer that emailed me about this if he would be willing to test different settings and he agreed. I just got home from work and had enough time to put this new library in my app and do some quick tests, but I hope to send him a test version later tonight. I hope that some of my tests work and stop the vibrations for him.

Thanks so much for not only making a custom version for me but also for doing it so quickly!

:sign0060:
 

Kevin

Well-Known Member
Licensed User
Longtime User
I noticed something else (this is just an observation and not a request):

It seems like the built-in B4A notification object must set the AlertOnce Android notification option to False. Is this correct?

With my testing, I noticed that when I set the B4A Notification object to Vibrate=True that my app vibrates when the notification first appears and also when it is updated with different text. I am seeing this also in your new library.

But with your original library, I was setting the AlertOnce option to True and it only vibrated when the notification was first displayed. Subsequent updates to the notification did not cause it to vibrate again.

Again, I am not asking for this option (whether you put it in or not is up to you), just wondering.

Whether your new library has this option or not doesn't really make a difference to me either way. If I am able to stop the vibrations on the customer's phone by specifying a vibration pattern of "0,0,0" then I couldn't care less if it wants to "vibrate" every time I update it or only when it first appears. If my trick doesn't work, then I am no worse off than before by just setting vibration to False like it always has been set.


Thanks again for the new custom custom notification library! Earlier today when I was reading this forum from my phone I decided I was going to "thank" you or give you an "award" but I guess this forum doesn't have those options. Perhaps it should! I must have been thinking of another forum.


So this will have to do:

:wav:
:sign0098: :sign0162: :icon_clap:
 

barx

Well-Known Member
Licensed User
Longtime User
In the spare of the moment I hadn't realised AlertOnce wasn't available in the b4a object. Thanks for pointing this out. I will add it this evening (similar time to yesterday ;)) and upload an update.

The message of appreciation will do fine. It's what makes these things worth while. Knowing you are helping other ;)
 

barx

Well-Known Member
Licensed User
Longtime User
In fact here you go, just added it. Saves you waiting round all day for me then ;)

Although not had time to test as it's time to go work, but it should work ok.
 

Attachments

  • AdvancedNotification.zip
    4.3 KB · Views: 309

Kevin

Well-Known Member
Licensed User
Longtime User
You're quick! I'm at work now anyway, but I can test it later on. Again, I don't really need this, but assuming you want all the options possible short of a custom layout then I figured I'd mention it. I can't recall if there were any other options missing in the stock notification object or not but I will check that later too.

I sent my test version to my customer last night and he said he would test when he has some time. I'll let you know the results.

Thanks again! I need to learn how to do this stuff. Sounds handy to know!
 

barx

Well-Known Member
Licensed User
Longtime User
You're quick! I'm at work now anyway, but I can test it later on. Again, I don't really need this, but assuming you want all the options possible short of a custom layout then I figured I'd mention it. I can't recall if there were any other options missing in the stock notification object or not but I will check that later too.

I sent my test version to my customer last night and he said he would test when he has some time. I'll let you know the results.

Thanks again! I need to learn how to do this stuff. Sounds handy to know!

He he, I try to help where i can and sometimes fast help really helps and it's sounds like your on a time schedule to sort an existing customer.

As for the library, I want to add anything that will be useful, this will probably be everything bar the custom layouts.

As for learning to create libraries...... I don't find it easy and I don't believe I'm on my own. It took me over 3 weeks of going crazy to figure out the custom notification library, and this one is pretty much a copy and paste job of the right parts from my custom library and the b4a original. I appear to have become a notification guru lol. But I have little other library knowledge
.
.
...yet.
 

Kevin

Well-Known Member
Licensed User
Longtime User
The new AlertOnce option works great! Again, these aren't needed by me, but I compared your new one against your original and other than things related to custom layouts, the only things I noticed that were missing were SetCustomLED and SetCustomSound. Other than that I would say this is a perfect and complete alternative to your other library for those who don't want or need custom layouts. Awesome work! :)

Fortunately, the customer who is helping test it wasn't too bothered by this problem after he figured out how to work around it on his phone's settings. However, I don't like the idea of something like this happening to other people because in my short experience with Android, most users are much more likely to uninstall and/or leave a bad rating for something like this rather than send the developer an email. If my app gets bad ratings (other than those from people who fail to comprehend the basic requirements) then I want it to be something that is my fault, not something like this that is through no direct fault of my own. If I can fix it or prevent it, I will! And although I haven't heard back yet, I am hopeful that tricking the phone into "vibrating" for 0ms will do the trick. Your library (and especially this new alternative) will have been a huge help if this works! My fingers are crossed!

If I am not mistaken, creating custom libraries requires Eclipse? Before discovering B4A, I played with Eclipse for several days. I've been programming in VB for many years and have even dabbled in Perl (by necessity, not preference!) and I could not figure out anything in Eclipse. Very frustrating for me. I'm sure I would have figured it out eventually but then I still would have had to teach myself java. Ugh. That was when I once again searched Google for some kind of easy alternative (other than that way-too-simple Google thing) and stumbled on B4A. I never would have written an Android app if not for B4A, and even if I did, I never would have made as much progress as I have with it in so little time.

Thanks to the hard work of Erel and many others on this forum such as yourself, we have a very powerful Android development tool at our disposal!

:sign0188:
 

barx

Well-Known Member
Licensed User
Longtime User
Any news yet kevin?
 

Kevin

Well-Known Member
Licensed User
Longtime User
Not yet. He said it may be a while due to his work schedule and I certainly didn't want to rush him since he is doing me a favor by testing it. It is a holiday weekend here in the states, so hopefully he will have enough extra time to test it out over the weekend.

Unless he works hours like me, where there essentially is no such thing as weekends and holidays. :)
 

Kevin

Well-Known Member
Licensed User
Longtime User
Still no word yet. I emailed him yesterday to see if he had a chance to test it yet but I haven't heard back. Perhaps he is busy or perhaps he decided he doesn't want to bother with it. I had included several different tests to try (by selecting a different method for showing the notification) and perhaps I made it sound more difficult than it was by over-explaining things. I tend to do that quite often.

Hopefully I will hear back soon. Otherwise I will have to wait until another customer contacts me with that same problem.

Unless someone on this forum has a Droid Charge and wants to test it for me. :)
 

barx

Well-Known Member
Licensed User
Longtime User
Its a shame that. Would have been good to get that one sorted.

Sent from my HTC Desire Z
 

Kevin

Well-Known Member
Licensed User
Longtime User
Well, I heard back from the customer but I am confused by the results.

He said that every test did exactly the same thing. I really don't understand this at all.

Here is part of the code from my test app. It seems to me they should do different things, and they do on my phone! :confused:

B4X:
Dim iOption As Int, listOption As List, txtOpt As String
   If listOption.IsInitialized = False Then listOption.Initialize
   listOption.Clear
   
   listOption.Add ("Original Notification")
   listOption.Add ("Test A (four long vibrations)")
   listOption.Add ("Test B (no vibrations)")
   listOption.Add ("Test C (vibrations set to 0ms)")
   listOption.Add ("Test D (Device Defaults)")   
   
   iOption = InputList (listOption,"Notification Test",-1)
   If iOption = DialogResponse.CANCEL Then Return
   Select Case iOption
      Case 0 'Original
         Common.ToggleNotificationIcon (True)  ' Call built-in B4A notification object in Common code module
         Return
      Case 1 'Test A  (four long vibrations)
         txtOpt = "Test A: 4 long vibrations"
         Dim v() As Long
         v = Array As Long (0,320,70,320,70,320,70,320)  ' Vibration pattern.  Format:  Initial Delay,On Time,Off Time,On Time,etc)
         an.Initialize
         an.Icon = "icon":an.AutoCancel = False:an.Light = False:an.Sound = False:an.Vibrate = False:an.OnGoingEvent = True:an.SetCustomVibrate (v):an.AlertOnce = True
      Case 2 'Test B  (no vibrations)
         txtOpt = "Test B: No vibrations"
         an.Initialize
         an.Icon = "icon":an.AutoCancel = False:an.Light = False:an.Sound = False:an.Vibrate = False:an.OnGoingEvent = True:an.AlertOnce = True
      Case 3 'Test C  (vibrations set to 0ms)
         txtOpt = "Test C: 0ms vibrations"
         Dim v() As Long
         v = Array As Long (1,0,1)  ' Vibration pattern.  Format:  Initial Delay,On Time ms,Off Time ms,On Time ms,etc)
         an.Initialize
         an.Icon = "icon":an.AutoCancel = False:an.Light = False:an.Sound = False:an.Vibrate = False:an.OnGoingEvent = True:an.SetCustomVibrate (v):an.AlertOnce = True
      Case 4 'Test D  (Device Defaults)
         txtOpt = "Test D: Device defaults"
         an.Initialize
         an.Icon = "icon":an.AutoCancel = False:an.Light = True:an.Sound = True:an.Vibrate = True:an.OnGoingEvent = True:an.AlertOnce = True
   End Select

If Common.STBName <> "" Then
  an.SetInfo("DirecTV Remote", Common.STBName & " (" & txtOpt & ")", "") 'Change Main to "" if this code is in the main module.
    Else
      an.SetInfo("DirecTV Remote", "Press here to use the remote" & " (" & txtOpt & ")", "") 'Change Main to "" if this code is in the main module.
End If
an.Notify (1)
 

barx

Well-Known Member
Licensed User
Longtime User
Originally it had that feature but not many devices support it. I didn't have such a device for testing so removed it. I guess I could add it again, but you cannot guarantee that the users' device will support.
 

Inman

Well-Known Member
Licensed User
Longtime User
Hello mate. I was using your Advanced Notification library till now and it was working very well. Then I thought of providing the user with the ability to set a custom notification ring tone and so I switched to your Custom Notifications library. I am facing a couple of issues now.

1. I can't get custom notification tones to work. I use AHPreferenceActivity where the user is shown the notification tone picker. When the user selects a ringtone, it returns a string like this:

content://media/internal/audio/media/31

I tried this string with n.SetCustomSound but it always plays the default ring tone. I tried replacing content:// with file:// and the result is still the same. How can I get this to work?

2. The second issue is with the actual notification. I didn't create any of my own styles and used your basic layout 1 (two text fields plus icon). I set n.setIcon correctly as my notification icon is different from app icon. Now when the notification happens, I see the correct icon on the status bar. But when I pull down the status bar to take a look at the notification, I see my app icon on the left side of the notification text, instead of notification icon. How can I fix it?
 

barx

Well-Known Member
Licensed User
Longtime User
Sorry for missing this. Here are my thoughts.

1) I personally haven't testing this feature, NJDude did though and reported it to work. He uses the feature in the example he provided near the beginning of this thread. From the documentation I read I appears the path needs to begin file:/// (note 3 x /). Check out the example to see how he does ;)

2) You found a bug :signOops: Yes it always uses "icon". Which is the app icon. I will change it for you, hopefully withing the next 2-3 hours and update. Also, the advanced notification lib was never officially released (due to lack of time) but the customSound routine can also be added to this library if you prefer...?

Thanks
 
Top