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

Inman

Well-Known Member
Licensed User
Longtime User
I am starting to understand why the custom sound feature is not working when you try it with some of the native sound files like ringtones. The AHPreferenceActivity returns the URI of the ringtone like this:

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

But that is just the URI and NOT the path. Even if you change content:// to file:///, it still won't give you the actual path in the internal system, which is file:///system/media/audio/notifications/Beat_Box_Android.ogg

I was looking for a code to convert URI to it's real path and found this reply by Erel

http://www.b4x.com/forum/basic4andr...orials/13473-uri-content-media-real-file.html

So now I am getting the correct path file:///system/media/audio/notifications/Beat_Box_Android.ogg. But unfortunately SetCustomSound is still not working even with the correct path. I wonder why.

As for adding customsound routine to advancednotification, I am ok with using customnotification. I like the extra features and might explore custom layouts in the future.
 

barx

Well-Known Member
Licensed User
Longtime User
Ok, take a look Here. Scroll down to the adding a sound section. Are you accessing the media with an intent like the 'MediaStore' example in that section. The CustomSound Method uses uri.parse (like the first example in that section). Also try making the
B4X:
cn.DefaultSound = false

Didn't get time to finish the mods to the lib last night, very nearly done though and will be uploaded later when I get home from work.

thanks
 

Inman

Well-Known Member
Licensed User
Longtime User
Ah yes. Setting DefaultSound = False did the trick. It works even with the content:// URI itself, without the need to convert to it's file:// path.
 

barx

Well-Known Member
Licensed User
Longtime User
Ah yes. Setting DefaultSound = False did the trick. It works even with the content:// URI itself, without the need to convert to it's file:// path.

Brilliant, I've also update the lib. Re-download from 1st post.

Hopefully should sort it out. Unfortunately not had time to test. Let me know how you get on with it. thanks.

Guess i better make Advance Notification official when i get a minute. Didn't realise anybody was using it...
 

Inman

Well-Known Member
Licensed User
Longtime User
Tested layout 1 and now it shows the correct notification icon. Thanks man.

And yes, you should make Advance Notification official, if possible with CustomSound as well. Will be incredibly useful for users who are looking for just the basic layout + added features.
 
Last edited:

Inman

Well-Known Member
Licensed User
Longtime User
I just noticed that custom notification doesn't show the time of notification on the right side, as in phone's default notification. Since the previous version of my app already has that (from Advanced Notification library), I think the users will notice the missing time stamp.

So, could you please update Advanced Notification library with SetCustomSound?

Or is it possible to add another layout to Custom Notification, which basically adds time stamp to the left of layout 1?
 
Last edited:

barx

Well-Known Member
Licensed User
Longtime User
You can add youe own xml layouts and add the required data fields. The presets are there for example and can be editted as required.

But I think you best option would be the advanced lib which I will update and release when I can. Currently on vacation so not getting much computer time. Will try to get it done in next 24 hrs. Thanks

Sent from my HTC Desire Z
 

Inman

Well-Known Member
Licensed User
Longtime User
Thanks man. Sorry I didn't know you were on vacation. I will wait for your update.
 

barx

Well-Known Member
Licensed User
Longtime User
No worries Inman, needed an excuse to get laptop out anyway.

Take a look here

For obvious reasons I have not tested 100% but all I have done is add documentation and copy some methods from the Custom Notification Library.
 

Inman

Well-Known Member
Licensed User
Longtime User
Thanks man. New library works perfectly, with CustomSound too.

Enjoy your vacation :D
 

barx

Well-Known Member
Licensed User
Longtime User
Glad to hear it. Cheers mate.

By all means still post any issues. I may just take longer to reply ;)

Sent from my HTC Desire Z
 

walterf25

Expert
Licensed User
Longtime User
Error Help

Hello all, i need some help, i have been implementing the custom notifications library for quite some time on one of my apps, i have been receiving some errors from some customers, i'm trying to debug what the problem is but can not figure it out.

this is the error i get from the logs:

android.app.RemoteServiceException: Bad notification posted from package com.dandre.apps: Couldn't expand RemoteViews for: StatusBarNotification(package=com.dandre.apps id=2 tag=null notification=Notification(vibrate=default,sound=default,defaults=0xffffffff,flags=0x10))


at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1081)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3806)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)

I just updated this library to 1.1 and it still gives me the same error, i have all the xml files where they belong but still get same error,

hope anyone can help me figure out why i get this error, and hopefully how to resolve it.

Thanks guys!
 

barx

Well-Known Member
Licensed User
Longtime User
Hello all, i need some help, i have been implementing the custom notifications library for quite some time on one of my apps, i have been receiving some errors from some customers, i'm trying to debug what the problem is but can not figure it out.

this is the error i get from the logs:



I just updated this library to 1.1 and it still gives me the same error, i have all the xml files where they belong but still get same error,

hope anyone can help me figure out why i get this error, and hopefully how to resolve it.

Thanks guys!

Walter, any chance you can post your notification code or pm it me, thx
 

Inman

Well-Known Member
Licensed User
Longtime User
I am starting to learn custom XML layouts. I see that I can set a custom layout for notification the library. I have two doubts.

Which all views are allowed in the notification bar custom layout?

Is it possible to design a music player control like notification, like in the bottom part of the screenshot?

nlfzH.jpg
 

melamoud

Active Member
Licensed User
Longtime User
using the lib as part of a service

hi,

I'm trying to use the lib as part of a service, but when I Do
Dim n As CustomNotification in the Process_Globals section
I get a compliation error
B4X:
Compiling code.                         Error
Error compiling program.
Error description: Cannot access activity object from sub Process_Globals.
Occurred on line: 16
Dim n As CustomNotification' the notification var that notify the user on the connectivity
Word: customnotification

is this a limitation or am I doing something wrong (it was working with the standard notification object

thanks
 

barx

Well-Known Member
Licensed User
Longtime User
Cannot say i've tried in it in Process_Globals. Whenever I use it in service I declare in Service_Start.
 

melamoud

Active Member
Licensed User
Longtime User
in servcie

Can you try and see if that can be fixed ?
defining it in the servcie_start is not going to work for me, since I need to keep it global, have the UI access it (to update the attricbutes)

thanks
 

basicall

Member
Licensed User
Longtime User
:sign0098: I have tested the lib. It could work well with my moto.

Sir, could you add a property to this lib for setting LED indicator color ? For example if battery in low power status we need to flash with red color but not green color ?
 
Top