Android Code Snippet Custom notifications channel

Discussion in 'Code Snippets' started by Erel, Apr 8, 2018.

  1. Erel

    Erel Administrator Staff Member Licensed User

    Starting from Android 8, notifications are grouped by channels. The notification behavior depends on the channel it belongs to.
    With B4A v8+ notification channels are created automatically based on the importance level.

    You can use the following code to manually create a notification channel with the same id as the notification channel that will be created internally. This allows you to override the notification behavior.

    Note that once a notification channel was created then you cannot change its behavior. This means that:

    1. You must call this code before you initialize the notification object.
    2. If you have already created a notification in the past then you need to uninstall the app to see the changes (clean the project afterward).

    Code:
    Sub CreateNotificationChannel(ImportanceLevel As Int)
       
    Dim p As Phone
       
    If p.SdkVersion >= 26 Then
           
    Dim ctxt As JavaObject
           ctxt.InitializeContext
           
    Dim channelId As String = "channel_" & ImportanceLevel
           
    Dim channel As JavaObject
           channel.InitializeNewInstance(
    "android.app.NotificationChannel"Array(channelId, Application.LabelName, ImportanceLevel))
           
    'modify the channel
           'For example: disable the badge feature
           channel.RunMethod("setShowBadge"Array(False))
           
           
    'set it
           Dim manager As JavaObject = ctxt.RunMethod("getSystemService"Array("notification"))
           manager.RunMethod(
    "createNotificationChannel"Array(channel))
           
       
    End If
    End Sub
    Example:
    Code:
    Dim n As Notification
       CreateNotificationChannel(n.IMPORTANCE_HIGH)
       n.Initialize2(n.IMPORTANCE_HIGH)
       n.Icon = 
    "icon"
       n.SetInfo(
    "test""test", Main)
       n.Notify(
    1)
    Depends on: Phone and JavaObject libraries. Requires B4A v8+
     
    js1234, lemonisdead, fredo and 2 others like this.
  2. Peter Simpson

    Peter Simpson Expert Licensed User

    Hello @Erel,
    The above code does appear to be working on all my devices both old and new.

    Anyway, thank you again for the above fully working code.
     
    Last edited: Apr 11, 2018
  3. Erel

    Erel Administrator Staff Member Licensed User

    Note that this code is only needed if you want to modify the channel. The built-in notification object (B4A v8+) will work on all devices as well.
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice