Android Question Recover title and message from firebase

Isac

Active Member
Licensed User
Longtime User
How can I recover the title and message that comes from firebase and then insert it into a Main.EditText1.text?

B4X:
#Region  Service Attributes
    #StartAtBoot: False
    
#End Region

Sub Process_Globals
    Private fm As FirebaseMessaging
    
End Sub

Sub Service_Create
    fm.Initialize("fm")
    
End Sub

Public Sub SubscribeToTopics
    fm.SubscribeToTopic("all") 'you can subscribe to more topics
End Sub

Sub Service_Start (StartingIntent As Intent)
    If StartingIntent.IsInitialized Then fm.HandleIntent(StartingIntent)
    Sleep(0)
    Service.StopAutomaticForeground 'remove if not using B4A v8+.
    
End Sub

Sub fm_MessageArrived (Message As RemoteMessage)
    Log("Message arrived")
    Log($"Message data: ${Message.GetData}"$)
    Dim n As Notification
    n.Initialize
    n.Icon = "icon"
    n.SetInfo(Message.GetData.Get("title"), Message.GetData.Get("body"),Main)  '<-----------
    n.Notify(1)
    Main.EditText1.text   '<---------------
      
    n.Vibrate=True
End Sub

Sub Service_Destroy

End Sub
 

KMatle

Expert
Licensed User
Longtime User
It depends on how and what you send. Take a look at "message.getdata". The easiest way is to send a DATA message which carrys a JSON string. Here you can put all data you like unless it's less or equal 4 KB. Use the search function here or Google for the different types of FCM messages (data, notification only and mixed, depending on the JSON you use when calling Googles API)
 
Upvote 0

Isac

Active Member
Licensed User
Longtime User
ok but I can not recall the Main.EditText1.text I do not see it in the intellisens.


B4X:
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region
'#BridgeLogger:true
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Dim EditText1 As EditText
    
    
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("Layout1")
    
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub
 
Upvote 0

Isac

Active Member
Licensed User
Longtime User
Erel can not find the argument to assign the message to the edittext1

thank you

Main

B4X:
Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
       Activity.LoadLayout("Layout1")
    EditText1.Text=CallSub2(FirebaseMessaging,"fm_MessageArrived", which argument?? )
End Sub

-------------------------------------------------------
FirebaseMessaging

B4X:
Sub fm_MessageArrived (Message As RemoteMessage)
    Log("Message arrived")
    Log($"Message data: ${Message.GetData}"$)
    Dim n As Notification
    n.Initialize
    n.Icon = "icon"
     n.SetInfo(Message.GetData.Get("title"), Message.GetData.Get("body"),Main)
    n.Notify(1)
    n.Vibrate=True
    
End Sub
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
There are many mistakes in the code you posted.

1. You should move n.Vibrate before calling n.SetInfo or your app will crash (assuming that you are using B4A v8+).
2. You should never call fm_MessageArrived yourself.

You can do something like this:
B4X:
Sub fm_MessageArrived (Message As RemoteMessage)
    Log("Message arrived")
    Log($"Message data: ${Message.GetData}"$)
    Dim n As Notification
    n.Initialize
    n.Icon = "icon"
     n.SetInfo(Message.GetData.Get("title"), Message.GetData.Get("body"),Main)
    n.Notify(1)
    CallSub2(Main, "SetText", Message.GetData.Get("title"))
    
End Sub
In the activity:
B4X:
Sub SetText (Title As String)
 EditText1.Text = Title

Will it be useful? Not too much as it will only work with messages that arrive while the activity is visible.
 
Upvote 0

Isac

Active Member
Licensed User
Longtime User
Thanks Erel,

I tried to insert a StartActivity(Main) inside Sub Service_Start (StartingIntent As Intent) but I can not recover the message when the activity is not open.
Is there a way to recover the message when the activity is not open?
for example when I press on the message arrived.



B4X:
Sub Service_Start (StartingIntent As Intent)
    StartActivity(Main)
    If StartingIntent.IsInitialized Then fm.HandleIntent(StartingIntent)
    Sleep(0)
    Service.StopAutomaticForeground 'remove if not using B4A v8+.
    
End Sub

Sub fm_MessageArrived (Message As RemoteMessage)
    Log("Message arrived")
    Log($"Message data: ${Message.GetData}"$)
    Dim n As Notification   
    n.Initialize
    n.Icon = "icon"
    n.Vibrate=True
     n.SetInfo(Message.GetData.Get("title"), Message.GetData.Get("body"),Main)
    n.Notify(1)
    CallSub2(Main, "SetText", Message.GetData.Get("title"))
    
End Sub
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
for example when I press on the message arrived.
You can store info in the Notification and later get them back when you click on the notif which then opens your app.

Get inspired here. It shows how to store the info and also the way to get the info back in your activity. Feel free to use the info then to update your label or whatever
 
Upvote 0

Isac

Active Member
Licensed User
Longtime User
Don Manfred, can you give me a simple example? the example you proposed is too complex.

for example: CallSub2 (Main, "SetText", Message.GetData.Get ("title")) should I delete it?


Thanks bye

B4X:
#Region  Service Attributes
    #StartAtBoot: False
    
#End Region

Sub Process_Globals
    Private fm As FirebaseMessaging
    
End Sub

Sub Service_Create
    fm.Initialize("fm")

End Sub

Public Sub SubscribeToTopics
    fm.SubscribeToTopic("all") 'you can subscribe to more topics
End Sub

Sub Service_Start (StartingIntent As Intent)

    If StartingIntent.IsInitialized Then fm.HandleIntent(StartingIntent)
    Sleep(0)
    Service.StopAutomaticForeground 'remove if not using B4A v8+.
    
End Sub



Sub fm_MessageArrived (Message As RemoteMessage)
    Log("Message arrived")
    Log($"Message data: ${Message.GetData}"$)
    Dim n As Notification
    n.Initialize
    n.Icon = "icon"
    n.Vibrate=True
    n.SetInfo(Message.GetData.Get("title"), Message.GetData.Get("body"),Main)
    n.Notify(1)
    CallSub2(Main, "SetText", Message.GetData.Get("title"))
    
End Sub

Sub Service_Destroy

End Sub



B4X:
#Region  Project Attributes
    #ApplicationLabel: Notify
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region
'#BridgeLogger:true
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    
    Dim Label3 As Label
    
    
End Sub   

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
       Activity.LoadLayout("Layout1")
    'EditText1.Text=CallSub2(FirebaseMessaging,"fm_MessageArrived", )
    
End Sub

Sub Activity_Resume
    
    
    
End Sub



Sub SetText (Title As String)
    Label3.Text = Title
End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub
 
Upvote 0

Isac

Active Member
Licensed User
Longtime User
Hi Erel can you give me a hand?
I tried this way, but I can not memorize the text and the title.
When I press on the message sent by firebase it should appear in the Main
inside the Label3.

thank you



MAIN

B4X:
#Region  Project Attributes

    #ApplicationLabel: Notify
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region
'#BridgeLogger:true
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    
    Dim Label3 As Label
    
    
End Sub   

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("Layout1")
    
    
End Sub

Sub Activity_Resume
    'Log("Auth.currentUser = "&auth.CurrentUser)

    Dim in As Intent = Activity.GetStartingIntent
        Dim intentExtra As String
      If in.HasExtra("title ") Then
    intentExtra = in.GetExtra("body")

            Dim jp As JSONParser
            jp.Initialize(intentExtra)
            Dim root As Map = jp.NextObject
            Dim OfferID As String = root.Get("title")
            Dim Title As String = root.Get("body")

        End If
    
End Sub

Sub SetText (Title As String)
Label3.Text = Title
End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

-----------------------------------------------------------------------------------------------------

FirebaseMessaging


B4X:
#Region  Service Attributes
    #StartAtBoot: False
    
#End Region

Sub Process_Globals
    Private fm As FirebaseMessaging
    
End Sub

Sub Service_Create
    fm.Initialize("fm")

End Sub

Public Sub SubscribeToTopics
    fm.SubscribeToTopic("all") 'you can subscribe to more topics
End Sub

Sub Service_Start (StartingIntent As Intent)
    If StartingIntent.IsInitialized Then fm.HandleIntent(StartingIntent)
    Sleep(0)
    Service.StopAutomaticForeground 'remove if not using B4A v8+.
    
End Sub

Sub fm_MessageArrived (Message As RemoteMessage)
    Log("Message arrived")
    Log($"Message data: ${Message.GetData}"$)

    Dim mapParameters As Map    : mapParameters.Initialize
    mapParameters.Put("title","HELLO")
    mapParameters.Put("body", "GOOD")
    Dim jgen As JSONGenerator
    jgen.Initialize(mapParameters)
    
    Dim n As NB6
    n.Initialize("default", Application.LabelName, "DEFAULT").AutoCancel(True)


    n.Build(Message.GetData.Get("title"), Message.GetData.Get("body"), jgen.ToString, Main).Notify(4)

End Sub
'    Log("Message arrived")
'    Log($"Message data: ${Message.GetData}"$)
'    Dim n As Notification
'    n.Initialize
'    n.Icon = "icon"
'    n.Vibrate=True
'    n.SetInfo(Message.GetData.Get("title"), Message.GetData.Get("body"),Main)
'    n.Notify(1)
'    CallSub2(Main, "SetText", Message.GetData.Get("title"))
    
'End Sub

Sub Service_Destroy

End Sub
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
Hi Erel can you give me a hand?
This is a community forum.- DON´T limit your question to a single member

Erel said a few days ago (in another thread) something like

"Posts starting with "Hi Erel", "Erel can you please" will be ignored as this is a community forum"

Firebasemessaging looks good. The Tag content is in the Notification_Tag

B4X:
'in globals
dim OldIntent as Intent

B4X:
Sub Activity_Resume
  Dim in As Intent = Activity.GetStartingIntent
    If in.IsInitialized And in <> OldIntent Then
        OldIntent = in
        Dim intentExtra As String
        If in.HasExtra("Notification_Tag") Then
            intentExtra = in.GetExtra("Notification_Tag")
            log("XTRA="&intentExtra)
            jp.Initialize(intentExtra)
            Dim root As Map = jp.NextObject
            Dim Title As String = root.Get("title")
            Dim Body As String = root.Get("body")
        End If
    End If
End Sub
 
Upvote 0

Isac

Active Member
Licensed User
Longtime User
It does not work, the messages do not arrive.

someone has some ideas?

B4X:
Sub Activity_Resume
    Dim in As Intent = Activity.GetStartingIntent
    If in.IsInitialized And in <> OldIntent Then
        OldIntent = in
        Dim intentExtra As String
        If in.HasExtra("Notification_Tag") Then
            intentExtra = in.GetExtra("Notification_Tag")
            Log("XTRA="&intentExtra)
            
            Dim jp As JSONParser
            jp.Initialize(intentExtra)
            Dim root As Map = jp.NextObject
            Dim Title As String = root.Get("title")
            Dim Body As String = root.Get("body")
        End If
    End If
End Sub

----------------------------------------------------------------------------------------

B4X:
Sub fm_MessageArrived (Message As RemoteMessage)
    Log("Message arrived")
    Log($"Message data: ${Message.GetData}"$)

    Dim mapParameters As Map    : mapParameters.Initialize
    mapParameters.Put("title","")
    mapParameters.Put("body", "")
    Dim jgen As JSONGenerator
    jgen.Initialize(mapParameters)
    
    Dim n As NB6
    n.Initialize("default", Application.LabelName, "DEFAULT").AutoCancel(True)
    
    n.Build(Message.GetData.Get("title"), Message.GetData.Get("body"), jgen.ToString, Main).Notify(4)
    
    End Sub
 
Upvote 0

Isac

Active Member
Licensed User
Longtime User
I can not understand, now the message arrives but is not recovered in the label3 when I press on the message.

thank you


--------------------
log:

Add #BridgeLogger: True to enable logs in Release mode.

--------------------


B4X:
#Region  Project Attributes
    #ApplicationLabel: Notify
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region
'#BridgeLogger:true
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Dim OldIntent As Intent
    Dim Label3 As Label
    
    
End Sub   

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("Layout1")
    
    
End Sub

Sub Activity_Resume
    Dim in As Intent = Activity.GetStartingIntent
    If in.IsInitialized And in <> OldIntent Then
        OldIntent = in
        Dim intentExtra As String
        If in.HasExtra("Notification_Tag") Then
            intentExtra = in.GetExtra("Notification_Tag")
            Log("XTRA="&intentExtra)
            Dim jp As JSONParser
            jp.Initialize(intentExtra)
            Dim root As Map = jp.NextObject
            Dim Title As String = root.Get("title")
            Dim Body As String = root.Get("body")
        End If
    End If
End Sub
    


'Sub SetText (Title As String)
'Label3.Text = Title
'End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub


-----------------------------------------------------


B4X:
#Region  Service Attributes
    #StartAtBoot: False
    
#End Region

Sub Process_Globals
    Private fm As FirebaseMessaging
    
End Sub

Sub Service_Create
    fm.Initialize("fm")

End Sub

Public Sub SubscribeToTopics
    fm.SubscribeToTopic("all") 'you can subscribe to more topics
End Sub

Sub Service_Start (StartingIntent As Intent)
    If StartingIntent.IsInitialized Then fm.HandleIntent(StartingIntent)
    Sleep(0)
    Service.StopAutomaticForeground 'remove if not using B4A v8+.
    
End Sub

Sub fm_MessageArrived (Message As RemoteMessage)
    Log("Message arrived")
    Log($"Message data: ${Message.GetData}"$)

    Dim mapParameters As Map    : mapParameters.Initialize
    mapParameters.Put("title","")
    mapParameters.Put("body", "")
    Dim jgen As JSONGenerator
    jgen.Initialize(mapParameters)
    Dim n As NB6
    n.Initialize("default", Application.LabelName, "DEFAULT").AutoCancel(True)
    n.Build(Message.GetData.Get("title"), Message.GetData.Get("body"), jgen.ToString, Main).Notify(4)
    
    End Sub
'    Log("Message arrived")
'    Log($"Message data: ${Message.GetData}"$)
'    Dim n As Notification
'    n.Initialize
'    n.Icon = "icon"
'    n.Vibrate=True
'    n.SetInfo(Message.GetData.Get("title"), Message.GetData.Get("body"),Main)
'    n.Notify(1)
'    CallSub2(Main, "SetText", Message.GetData.Get("title"))
    
'End Sub

Sub Service_Destroy

End Sub
 
Upvote 0

Isac

Active Member
Licensed User
Longtime User
Not understood how to write in the label3.text
is anyone kind enough to explain it to me?
I noticed that if the app is open and I send the message via b4j the app is "parked"

I have a warning indicating that these variables are not used

B4X:
    Dim Title As String = root.Get("Title")
    Dim Body As String = root.Get("Body")

I thank
 
Upvote 0

Isac

Active Member
Licensed User
Longtime User
What is the output of:
B4X:
Log(in)
Log(in.ExtrasToString)

I see nothing in the log file, should I set something on b4a?

B4X:
ub Activity_Resume
    
    Dim in As Intent = Activity.GetStartingIntent
    If in.IsInitialized And in <> OldIntent Then
        OldIntent = in
        Dim intentExtra As String
        If in.HasExtra("Notification_Tag") Then
            intentExtra = in.GetExtra("Notification_Tag")
            Log("XTRA="&intentExtra)
            Log(in) <-----------------------------------------
            Log(in.ExtrasToString) <-----------------------------------------
            Dim jp As JSONParser
            jp.Initialize(intentExtra)
            Dim root As Map = jp.NextObject
            Dim OfferID As String = root.Get("OfferID")
            Dim Title As String = root.Get("Title")
        End If
    End If
End Sub
 

Attachments

  • log.PNG
    log.PNG
    56.1 KB · Views: 268
Upvote 0

Isac

Active Member
Licensed User
Longtime User
but does the log file work only in debugging?

I found this error:


Logger connesso a: HUAWEI BLN-L21
--------- beginning of crash
--------- beginning of main
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
*** Service (firebasemessaging) Create ***
** Service (firebasemessaging) Start **
** Activity (main) Pause, UserClosed = false **
** Activity (main) Resume **
** Receiver (firebasemessaging) OnReceive **
** Service (firebasemessaging) Start **
Message arrived
Message data: {}
Error occurred on line: 289 (NB6)
java.lang.IllegalArgumentException: Invalid notification (no valid small icon): Notification(pri=0 contentView=null vibrate=default sound=default defaults=0x7 flags=0x11 color=0x00000000 vis=PRIVATE)
at android.app.NotificationManager.notifyAsUser(NotificationManager.java:318)
at android.app.NotificationManager.notify(NotificationManager.java:293)
at android.app.NotificationManager.notify(NotificationManager.java:277)
at anywheresoftware.b4a.objects.NotificationWrapper.Notify(NotificationWrapper.java:281)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.shell.Shell.runMethod(Shell.java:735)
at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:357)
at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:260)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:144)
at anywheresoftware.b4a.BA$1.run(BA.java:330)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)




NB6

B4X:
1.00
Sub Class_Globals
    Private Channel As JavaObject
    Private NotificationBuilder As JavaObject
    Private SdkLevel As Int
    Private ctxt As JavaObject
    Private const S_OLD = 0, S_BUILDER = 1, S_CHANNEL = 2 As Int
    Private SupportLevel As Int
    Private OldNotification As Notification
    Private PendingIntentStatic As JavaObject
    Private NotificationStatic As JavaObject
    Private common As JavaObject
    
End Sub

'Initializes the builder.
'ChannelId - On Android 8+ notifications are grouped by channels. Some of the features belong to the channel
' and not to the specific notification.
' Note that once a notification channel is created, you cannot change its behavior without uninstalling the app.
' NB6 adds the notification level string to the ChannelId so in most cases you can use the same value for all notifications.
'Channel Name - The channel name that appears when pressing on All Categories button (Android 8+).
'ImportanceLevel - MIN, LOW, DEFAULT, HIGH
'MIN - Minimum interrup. Cannot be used with foreground services.
'LOW - Without sound.
'DEFAULT - With sound.
'HIGH - Might appear as a headup notification.
Public Sub Initialize (ChannelId As String, ChannelName As Object, ImportanceLevel As String) As NB6
    ctxt.InitializeContext
    PendingIntentStatic.InitializeStatic("android.app.PendingIntent")
    NotificationStatic.InitializeStatic("android.app.Notification")
    common.InitializeStatic("anywheresoftware.b4a.keywords.Common")
    Dim jo As JavaObject
    SdkLevel = jo.InitializeStatic("android.os.Build$VERSION").GetField("SDK_INT")
    If SdkLevel < 23 Then
        SupportLevel = S_OLD
    Else if SdkLevel >= 26 Then
        SupportLevel = S_CHANNEL
    Else
        SupportLevel = S_BUILDER
    End If
    If IsOld Then
        OldNotification.Initialize
        OldNotification.Icon = "icon"
    Else if IsChannel Then
        ChannelId = ChannelId & "_" & ImportanceLevel
        NotificationBuilder.InitializeNewInstance("android.app.Notification$Builder", Array(ctxt, ChannelId))
        Dim im As Map = CreateMap("MIN": 1, "LOW": 2, "DEFAULT": 3, "HIGH": 4)
        Dim i As Int = im.Get(ImportanceLevel)
        Channel.InitializeNewInstance("android.app.NotificationChannel", Array(ChannelId, Application.LabelName, i))
    Else
        NotificationBuilder.InitializeNewInstance("android.app.Notification$Builder", Array(ctxt))
        Dim pm As Map = CreateMap("MIN": -2, "LOW": -1, "DEFAULT": 0, "HIGH": 1)
        Dim p As Int = pm.Get(ImportanceLevel)
        NotificationBuilder.RunMethod("setPriority", Array(p))
    End If
    If ImportanceLevel = "DEFAULT" Or ImportanceLevel = "HIGH" Then
        SetDefaults(True, True, True)
    Else
        SetDefaults(False, True, True)
    End If
    Return Me
End Sub

'Adds a button action.
'Bmp - Button image. Not always appears.
'Title - Button title (CharSequence)
'Service - The service that will receive the action. <b>Cannot be the Starter service.</b>
'Action - The action in the StartingIntent.
Public Sub AddButtonAction (Bmp As Bitmap, Title As Object,  Service As Object, Action As String) As NB6
    If IsBuilder = False Then Return Me
    Dim ac As Object = CreateAction(Bmp, Title, CreateReceiverPendingIntent(Service, Action))
    NotificationBuilder.RunMethod("addAction", Array(ac))
    Return Me
End Sub

'Action intent that will be sent when the notification is deleted.
'Service - The service that will receive the action. <b>Cannot be the Starter service.</b>
'Action - The action in the StartingIntent.
Public Sub DeleteAction (Service As Object, Action As String) As NB6
    If IsBuilder Then
        NotificationBuilder.RunMethod("setDeleteIntent", Array(CreateReceiverPendingIntent(Service, Action)))
    End If
    Return Me
End Sub

'Sets the notification icon on old devices. By default the app icon will be used.
Public Sub OldNotificationIcon (ResourceName As String) As NB6
    If IsOld Then
        OldNotification.Icon = ResourceName
    End If
    Return Me
End Sub

'Sets the status bar icon. The icon size should be 24 x 24.
Public Sub SmallIcon (Icon As Bitmap) As NB6
    If IsBuilder Then
        NotificationBuilder.RunMethod("setSmallIcon", Array(CreateIconFromBitmap(Icon)))
    End If
    Return Me
End Sub

'Sets the content icon. Should be 256 x 256.
Public Sub LargeIcon (Icon As Bitmap) As NB6
    If IsBuilder Then
        NotificationBuilder.RunMethod("setLargeIcon", Array(CreateIconFromBitmap(Icon)))
    End If
    Return Me
End Sub

'Only plays a sound if the notification is not already displayed.
Public Sub OnlyAlertOnce (Once As Boolean) As NB6
    If IsBuilder Then
        NotificationBuilder.RunMethod("setOnlyAlertOnce", Array(Once))
    End If
    Return Me
End Sub

'Cancels the notification when the user clicks on it.
Public Sub AutoCancel (Cancel As Boolean) As NB6
    If IsOld Then
        OldNotification.AutoCancel = Cancel
    Else
        NotificationBuilder.RunMethod("setAutoCancel", Array(Cancel))
    End If
    Return Me
End Sub

'One of the following values: NONE, SMALL, LARGE
'Not supported by all launchers.
Public Sub BadgeIconType (IconType As String) As NB6
    If SdkLevel >= 26 Then
        Dim m As Map = CreateMap("LARGE": 2, "NONE": 0, "SMALL": 1)
        NotificationBuilder.RunMethod("setBadgeIconType", Array(m.Get(IconType)))
    End If
    Return Me
End Sub

'Sets the accent color.
Public Sub Color (Clr As Int) As NB6
    If IsBuilder Then
        NotificationBuilder.RunMethod("setColor", Array(Clr))
    End If
    Return Me
End Sub

'Sets a number that might be displayed as a badge.
Public Sub Number (Num As Int) As NB6
    If IsOld Then
        OldNotification.Number = Num
    Else
        NotificationBuilder.RunMethod("setNumber", Array(Num))
    End If
    Return Me
End Sub

'Shows a timestamp
Public Sub ShowWhen (Time As Long) As NB6
    If IsBuilder Then
        NotificationBuilder.RunMethod("setShowWhen", Array(True))
        NotificationBuilder.RunMethod("setWhen", Array(Time))
    End If
    Return Me
End Sub

'Shows a progress bar. Cannot be used with SubText.
'Value - Current value.
'MaxValue - Maximum value.
'Indeterminate - Set to true for an indeterminate progress bar.
Public Sub Progress (Value As Int, MaxValue As Int, Indeterminate As Boolean) As NB6
    If IsBuilder Then
        NotificationBuilder.RunMethod("setProgress", Array(MaxValue, Value, Indeterminate))
    End If
    Return Me
End Sub

'Additional text. Occupies the same place as the progress bar so do not use both features.
Public Sub SubText (Text As Object) As NB6
    If IsBuilder Then
        NotificationBuilder.RunMethod("setSubText", Array(Text))
    End If
    Return Me
End Sub

'Set which features will be inherited from the system defaults.
'The defaults are also set based on the importance level.
Public Sub SetDefaults (Sound As Boolean, Light As Boolean, Vibrate As Boolean) As NB6
    If IsOld Then
        OldNotification.Sound = Sound
        OldNotification.Light = Light
        OldNotification.Vibrate = Vibrate
    Else
        If IsChannel Then
            Channel.RunMethod("enableLights", Array(Light))
            Channel.RunMethod("enableVibration", Array(Vibrate))
        Else
            Dim CurrentDefaults As Int
            If Sound Then CurrentDefaults = 1
            If Vibrate Then CurrentDefaults = Bit.Or(CurrentDefaults, 2)
            If Light Then CurrentDefaults = Bit.Or(CurrentDefaults, 4)
            NotificationBuilder.RunMethod("setDefaults", Array(CurrentDefaults))
        End If
    End If
    Return Me
End Sub

'Sets a custom sound.
'The uri must be created with FileProvider.
Public Sub CustomSound (FileProviderUri As Object) As NB6
    If IsOld Then Return Me
    ctxt.RunMethod("grantUriPermission", Array("com.android.systemui", FileProviderUri, 1))
    If IsBuilder Then
        NotificationBuilder.RunMethod("setSound", Array(FileProviderUri, NotificationStatic.GetField("AUDIO_ATTRIBUTES_DEFAULT")))
        If IsChannel Then
            Channel.RunMethod("setSound", Array(FileProviderUri, NotificationStatic.GetField("AUDIO_ATTRIBUTES_DEFAULT")))
        End If
    End If
    Return Me
End Sub

'Possible values: PUBLIC, PRIVATE or SECRET
'Default value is PRIVATE.
'PRIVATE - notification content will not appear above secure lock screen. Title and icon will appear.
'PUBLIC - notification content will apear everywhere.
'SECRET - notification will not appear at all above secure lock screen.
Public Sub Visibility (Value As String) As NB6
    If IsBuilder Then
        Dim m As Map = CreateMap("PUBLIC": 1, "SECRET": -1, "PRIVATE": 0)
        Dim i As Int = m.Get(Value)
        NotificationBuilder.RunMethod("setVisibility", Array(i))
    End If
    Return Me
End Sub

'Creates a "big picture" notification.
Public Sub BigPictureStyle(LargeIconBmp As Bitmap, Picture As Bitmap, ContentTitle As Object, SummaryText As Object) As NB6
    If IsBuilder Then
        SetStyle("android.app.Notification$BigPictureStyle", _
            CreateMap("bigLargeIcon": LargeIconBmp, _
                "bigPicture": Picture, _
                "setBigContentTitle": ContentTitle, _
                "setSummaryText": SummaryText))
    End If
    Return Me
End Sub

'Creates a "big text" notification.
Public Sub BigTextStyle (ContentTitle As Object, SummaryText As Object, Text As Object) As NB6
    If IsBuilder Then
        SetStyle("android.app.Notification$BigTextStyle", _
            CreateMap("bigText": Text, "setBigContentTitle": ContentTitle, "setSummaryText": SummaryText))
    End If
    Return Me
End Sub

Private Sub SetStyle(StyleName As String, Props As Map)
    Dim style As JavaObject
    style.InitializeNewInstance(StyleName, Null)
    For Each method As String In Props.Keys
        Dim value As Object = Props.Get(method)
        If value <> Null Then
            style.RunMethod(method, Array(value))
        End If
    Next
    NotificationBuilder.RunMethod("setStyle", Array(style))
End Sub

'Build the notification and returns the notification object.
'ContentTitle - Title (CharSequence)
'ContentText - Body text (CharSequence)
'Tag - Tag that can be intercepted in Activity_Resume when the user clicks on the notificaiton.
'Activity - The activity that will be launched when the user clicks on the notification.
Public Sub Build (ContentTitle As Object, ContentText As Object, Tag As String, Activity As Object) As Notification
    If IsOld Then
        OldNotification.SetInfo2(ContentTitle, ContentText, Tag, Activity)
        Return OldNotification
    Else
        Dim in As Intent = CreateIntent(Activity, False)
        in.Flags = Bit.Or(268435456, 131072) 'FLAG_ACTIVITY_NEW_TASK and FLAG_ACTIVITY_REORDER_TO_FRONT
        in.PutExtra("Notification_Tag", Tag)
        Dim PendingIntent As Object = PendingIntentStatic.RunMethod("getActivity", Array(ctxt, Rnd(0, 0x7fffffff), in, 0))
        NotificationBuilder.RunMethodJO("setContentTitle", Array(ContentTitle)).RunMethodJO("setContentText", Array(ContentText))
        NotificationBuilder.RunMethod("setContentIntent", Array(PendingIntent))
        
        If IsChannel Then
            Dim manager As JavaObject = ctxt.RunMethod("getSystemService", Array("notification"))
            manager.RunMethod("createNotificationChannel", Array(Channel))
            
        End If
        Return NotificationBuilder.RunMethod("build", Null)
    End If
End Sub

Private Sub CreateReceiverPendingIntent (Service As Object, Action As String) As Object
    Dim in As Intent = CreateIntent(Service, True)
    in.Action = Action
    Return PendingIntentStatic.RunMethod("getBroadcast", Array(ctxt, 1, in, 0))
End Sub

Private Sub CreateIntent (Target As Object, Receiver As Boolean) As Intent
    Target = common.RunMethod("getComponentClass", Array(Null, Target, Receiver))
    Dim in As JavaObject
    in.InitializeNewInstance("android.content.Intent", Array(ctxt, Target))
    Return in
End Sub

Private Sub CreateAction (Bmp As Bitmap, Title As Object, PendingIntent As Object) As Object
    Dim builder As JavaObject
    builder.InitializeNewInstance("android.app.Notification$Action$Builder", Array(CreateIconFromBitmap(Bmp), Title, PendingIntent))
    Return builder.RunMethod("build", Null)
End Sub

Private Sub CreateIconFromBitmap(bmp As Bitmap) As Object
    If bmp = Null Or bmp.IsInitialized = False Then Return 0
    Dim icon As JavaObject
    Return icon.InitializeStatic("android.graphics.drawable.Icon").RunMethod("createWithBitmap", Array(bmp))
End Sub

Private Sub IsBuilder As Boolean
    Return SupportLevel >= S_BUILDER
End Sub

Private Sub IsOld As Boolean
    Return SupportLevel = S_OLD
End Sub

Private Sub IsChannel As Boolean
    Return SupportLevel = S_CHANNEL
End Sub
 
Last edited:
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
I see nothing in the log file, should I set something on b4a?
YES!
log:

Add #BridgeLogger: True to enable logs in Release mode.
READ THIS! Add the Line to your project! Compile in Release mode and run the app throught bridge.

Sorry, but i give up here. I´m not interested on helping you any more.

Regarding the Threadsubject i posted a working code in #12
 
Upvote 0
Top