Android Code Snippet Version safe notification

Erel

Administrator
Staff member
Licensed User
Update: If you are using B4A v8.0+ then the standard notifications will work.
Make sure to call Notification.SetInfo as the last step before using the notification.

New class for more powerful notifications: NB6 - Notifications Builder class (2018)

Older versions:

As explained in this tutorial all store apps will soon be forced to target the latest SDK.

The following code can be used to create a notification. It works on all versions of Android.

B4X:
Private Sub CreateNotification(Title As String, Content As String, Icon As String, TargetActivity As Object, _
    Sound As Boolean, Vibrate As Boolean) As Notification
   Dim p As Phone
   If p.SdkVersion >= 21 Then
       Dim nb As NotificationBuilder
       nb.Initialize
       nb.DefaultSound = Sound
       nb.DefaultVibrate = Vibrate
       nb.ContentTitle = Title
       nb.ContentText = Content
       nb.setActivity(TargetActivity)
       nb.SmallIcon = Icon
       If p.SdkVersion >= 26 Then
           Dim ctxt As JavaObject
           ctxt.InitializeContext
           Dim manager As JavaObject
           manager.InitializeStatic("android.app.NotificationManager")
           Dim Channel As JavaObject
           Dim importance As String
           If Sound Then importance = "IMPORTANCE_DEFAULT" Else importance = "IMPORTANCE_LOW"
           Dim ChannelVisibleName As String = Application.LabelName
           Channel.InitializeNewInstance("android.app.NotificationChannel", _
                   Array("MyChannelId1", ChannelVisibleName, manager.GetField(importance)))
           manager = ctxt.RunMethod("getSystemService", Array("notification"))
           manager.RunMethod("createNotificationChannel", Array(Channel))
           Dim jo As JavaObject = nb
           jo.RunMethod("setChannelId", Array("MyChannelId1"))
       End If
       Return  nb.GetNotification
   Else
       Dim n As Notification
       n.Initialize
       n.Sound = Sound
       n.Vibrate = Vibrate
       n.Icon = Icon
       n.SetInfo(Title, Content, TargetActivity)
       Return n
   End If
End Sub
Libraries: Phone, JavaObject and NotificationBuilder. Note that you need to add the following line for NotificationBuilder:
B4X:
#additionaljar: com.android.support:support-v4
You can modify the code and customize the notification.

This code requires B4A v7.8+. Make sure to use B4A Sdk Manager and install all recommended items.
 
Last edited:

NJDude

Expert
Licensed User
I'm testing the code on a device running Android Oreo (8.0.0 - SDK 26) and I get this error:
B4X:
** Activity (main) Create, isFirst = true **
main_createnotification (java line: 409)
java.lang.RuntimeException: Method: setChannelId not found in: android.support.v4.app.NotificationCompat$Builder
	at anywheresoftware.b4j.object.JavaObject$MethodCache.getMethod(JavaObject.java:366)
	at anywheresoftware.b4j.object.JavaObject.RunMethod(JavaObject.java:119)
	at njdude.generic.sample.main._createnotification(main.java:409)
	at njdude.generic.sample.main._activity_create(main.java:333)
	at java.lang.reflect.Method.invoke(Native Method)
	at anywheresoftware.b4a.BA.raiseEvent2(BA.java:186)
	at njdude.generic.sample.main.afterFirstLayout(main.java:102)
	at njdude.generic.sample.main.access$000(main.java:17)
	at njdude.generic.sample.main$WaitForLayout.run(main.java:80)
	at android.os.Handler.handleCallback(Handler.java:789)
	at android.os.Handler.dispatchMessage(Handler.java:98)
	at android.os.Looper.loop(Looper.java:164)
	at android.app.ActivityThread.main(ActivityThread.java:6541)
	at java.lang.reflect.Method.invoke(Native Method)
	at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
java.lang.RuntimeException: Method: setChannelId not found in: android.support.v4.app.NotificationCompat$Builder
Am I missing something?
 

Peter Simpson

Expert
Licensed User
@NJDude I'm using the following code which I believe works perfect for me, please give it a go and let me know your results.
B4X:
    Dim NotificationInfo As NotificationBuilder
           NotificationInfo.Initialize
           NotificationInfo.SmallIcon = "icon"
           NotificationInfo.setActivity(Main)
           NotificationInfo.ContentTitle = "App Info"
           NotificationInfo.ContentText = "NotificationMessage"
           NotificationInfo.DefaultSound = True
           NotificationInfo.DefaultLight = True
           NotificationInfo.DefaultVibrate = True
           'NotificationInfo.setProgress(100, 75, False)
 
    Dim P As Phone
    If P.SdkVersion >= 26 Then
        Dim Ctxt As JavaObject
            Ctxt.InitializeContext
 
        Dim Manager As JavaObject
            Manager.InitializeStatic("android.app.NotificationManager")
        Dim Channel As JavaObject
 
        Dim ChannelVisibleName As String = "My Channel"
        Channel.InitializeNewInstance("android.app.NotificationChannel", Array("MyChannelId1", ChannelVisibleName, Manager.GetField("IMPORTANCE_DEFAULT")))
        Manager = Ctxt.RunMethod("getSystemService", Array("notification"))
        Manager.RunMethod("createNotificationChannel", Array(Channel))
 
        Dim Jo As JavaObject = NotificationInfo
            Jo.RunMethod("setChannelId", Array("MyChannelId1"))
    End If

    NotificationInfo.Notify(1)
 
Last edited:

Peter Simpson

Expert
Licensed User
Hey man, thanks for the code, but, I still get the same error.
Really, sorry to hear that as the code I posted works perfectly fine on my phone running Android 8.1.0, and inturn pushes notifications to my watches perfectly fine...
 

NJDude

Expert
Licensed User
Maybe is something on my end, but notifications in general work fine, it's just this particular code.

Thanks again.
 

martin24

Member
Licensed User
The "Sound" parameter doesn't work correctly with your code.

Seems that you cannot change the importance once a channel is created. See also https://stackoverflow.com/questions/45919392/disable-sound-from-notificationchannel

I tried the following work around which seems to work (not tested with Vibrate):

B4X:
Dim sChannelName As String
If Sound Then
    sChannelName = "MyChannelId1"
Else
    sChannelName = "MyChannelId2"
End If

Dim ctxt As JavaObject
ctxt.InitializeContext
Dim manager As JavaObject
manager.InitializeStatic("android.app.NotificationManager")
Dim Channel As JavaObject
Dim importance As String
If Sound Then importance = "IMPORTANCE_DEFAULT" Else importance = "IMPORTANCE_LOW"
Dim ChannelVisibleName As String = Application.LabelName
Channel.InitializeNewInstance("android.app.NotificationChannel", Array(sChannelName, ChannelVisibleName, manager.GetField(importance)))
manager = ctxt.RunMethod("getSystemService", Array("notification"))
manager.RunMethod("createNotificationChannel", Array(Channel))
Dim jo As JavaObject = nb
jo.RunMethod("setChannelId", Array(sChannelName))
 

KMatle

Expert
Licensed User
Do we really need the NotificationBuilder library? (as it is not a core library).
 

Semen Matusovskiy

Well-Known Member
Licensed User
I got java.lang.RuntimeException: Method: setChannelId not found in: android.support.v4.app.NotificationCompat$Builder

Android Oreo 8.0.0
... \platforms\android-27\android.jar
I installed all in B4A and Android Studio SDK manager

What can be wrong ? BTW, I don't understand how setChannelId (API 26.0.1) is able to work in Oreo 8.0.0
 
Top