Android Question Detect click from notification

Stevenindonesia

Member
Licensed User
How can i detect user launch application by notification?
I am using B4X and i tried below code :

B4X:
Sub Process_Globals
    Private LastIntent As Intent
End Sub

Sub Activity_Resume
    Dim in As Intent = Activity.GetStartingIntent
    If in.IsInitialized And in.HasExtra("Notification_Tag") And in <> LastIntent Then
        LastIntent = in
        Dim tag As String = in.GetExtra("Notification_Tag")
        Msgbox("User clicked notification: " & tag,"Message")
    End If
End Sub

I still couldn't capture the intent and message did not pop up.
 

Stevenindonesia

Member
Licensed User
Erel,

My application are able to get notification. But when i click on the notification... my application will launch. How can i detect that the user launch the application by clicking on notification?
What i wanted to do is - when user launch application by clicking in coming notification, I will show the notification page.


B4X:
Sub Process_Globals
    Private LastIntent As Intent
End Sub

Sub Activity_Resume
    Dim in As Intent = Activity.GetStartingIntent
    If in.IsInitialized And in.HasExtra("Notification_Tag") And in <> LastIntent Then
        LastIntent = in
        Dim tag As String = in.GetExtra("Notification_Tag")
        Log("User clicked notification: " & tag)
    End If
End Sub

The above code doesn't seems to work.
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
Erel asked you to post the code that generates the notification.

Where is that code?

You just posted the same code as in #1 of this thread.
 
Upvote 0

Stevenindonesia

Member
Licensed User
Erel, DonManfred,
We send the notification using PHP. Please find below code the JSON part that sends to Firebase :
B4X:
//**************************************************
//  SEND NOTIFICATION
//**************************************************
function sendNotificationToTopic($OS,$iprojectId,$itoken,$itopic, $ititle, $imessage){
    if($OS=="Android"){
        $data = [
            "message" => [
                "topic" => "AND_".$itopic,
                "data" => [
                    "title" => $ititle,
                    "body" => $imessage
                ],
                "apns" => [
                    "payload" => [
                        "aps" => [
                            "sound" => "default"
                        ]
                    ]
                ]
            ]
        ];
    }elseif($OS=="IOS"){
        $data = [
            "message" => [
                "topic" => "IOS_".$itopic,
                "notification" => [
                    "title" => $ititle,
                    "body" => $imessage
                ],
                "apns" => [
                    "payload" => [
                        "aps" => [
                            "sound" => "default"
                        ]
                    ]
                ]
            ]
        ];
    }
    $url = "https://fcm.googleapis.com/v1/projects/" . $iprojectId . "/messages:send";
    $headers = [
        "Authorization: Bearer " . $itoken,
        "Content-Type: application/json"
    ];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    $response = curl_exec($ch);
    if (curl_error($ch)) {
        die("CURL Error: " . curl_error($ch));
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    echo "HTTP Code: " . $httpCode . "\n";
    echo "Response: " . $response . "\n";
}


The notification arrived in both Android and IOS but when i click the notification, i couldnt 'catch' GetStartingIntent for both Android and IOS
 
Upvote 0

Stevenindonesia

Member
Licensed User
I have tested with B4J example - to send notification. I received notification from B4J but still couldn't capture the intent and message did not pop up. What possibly could be wrong?
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
What possibly could be wrong?
No one can tell if you insist in not posting the code that CREATES THE NOTIFICATION. God dammit.

This code is the place where you need to add the Notification_Tag which you are trying to capture. You already got told to add it in the notification in your receiver.
 
Upvote 0

Stevenindonesia

Member
Licensed User
DonMenfred,
If you not notice, Erel asked me to use B4J example (FCMPush) - from

Anyway below are the codes from B4J

B4X:
'Non-UI application (console / server application)
#Region  Project Attributes
    #CommandLineArgs:
    #MergeLibraries: True
#End Region
'Version: 2.00

#AdditionalJar: google-auth-library-oauth2-http-1.18.0.jar
#AdditionalJar: google-auth-library-credentials-1.18.0.jar
#AdditionalJar: guava-23.0.jar
#AdditionalJar: google-http-client-1.43.3.jar
#AdditionalJar: google-http-client-gson-1.43.3.jar
#AdditionalJar: gson-2.10.1.jar
#AdditionalJar: opencensus-api-0.31.1.jar
#AdditionalJar: opencensus-contrib-http-util-0.31.1.jar
#AdditionalJar: grpc-context-1.27.2.jar
#PackagerProperty: AdditionalModuleInfoString = uses com.google.auth.http.HttpTransportFactory;

Sub Process_Globals
    Private Const ProjectId As String = "dxnshop-cdd94" 'change
    Private ServiceAccountFilePath As String = "C:\Users\User\Desktop\B4J-SendingTool\FCMPush\dxnshopkey.json" 'change
    Private Token As String
End Sub

Sub AppStart (Args() As String)
    Send("HUDEVGROUP", "this is the title", "And this is the body")
    StartMessageLoop
End Sub

Private Sub Send (topic As String, title As String, body As String)
    Dim Token As String = GetTokenValue(ServiceAccountFilePath)
    Wait For (SendMessage("AND_" & topic, title, body)) Complete (Success As Boolean) 'B4A - commend if not needed
    Wait For (SendMessage("IOS_" & topic, title, body)) Complete (Success As Boolean) 'B4i - comment if not needed
    ExitApplication
End Sub

Private Sub SendMessage(Topic As String, Title As String, Body As String) As ResumableSub
    Dim Job As HttpJob
    Job.Initialize("", Me)
    Dim data As Map = CreateMap("title": Title, "body": Body)
    Dim message As Map = CreateMap("topic": Topic, "data": data)
    If Topic.StartsWith("IOS_") Then
        'B4i
        Dim Badge As Int = 0
        Dim iosalert As Map =  CreateMap("title": Title, "body": Body)
        message.Put("notification", iosalert)
        message.Put("apns", CreateMap("headers": _
            CreateMap("apns-priority": "10"), _
            "payload": CreateMap("aps": CreateMap("sound":"default", "badge": Badge))))
    Else
        'B4A
        message.Put("android", CreateMap("priority": "high"))
    End If
    Dim jg As JSONGenerator
    jg.Initialize(CreateMap("message": message))
    Log(jg.ToPrettyString(4))
    Job.PostString($"https://fcm.googleapis.com/v1/projects/${ProjectId}/messages:send"$, jg.ToString)
    Job.GetRequest.SetContentType("application/json;charset=UTF-8")
    Job.GetRequest.SetHeader("Authorization", "Bearer " & Token)
    Wait For (Job) JobDone(Job As HttpJob)
    If Job.Success Then
        Log(Job.GetString)
    End If
    Job.Release
    Return True
End Sub

Private Sub GetTokenValue (FilePath As String) As String
    Dim GoogleCredentials As JavaObject
    GoogleCredentials.InitializeStatic("com.google.auth.oauth2.GoogleCredentials")
    Dim Credentials As JavaObject = GoogleCredentials.RunMethodJO("fromStream", Array(File.OpenInput(FilePath, ""))) _
        .RunMethod("createScoped", Array(Array As String("https://www.googleapis.com/auth/firebase.messaging")))
    Credentials.RunMethod("refreshIfExpired", Null)
    Return Credentials.RunMethodJO("getAccessToken", Null).RunMethod("getTokenValue", Null)
End Sub

In my mobile app, I tried to capture by using intent

B4X:
Sub Process_Globals
    Private LastIntent As Intent
End Sub

Sub Activity_Resume
    Dim in As Intent = Activity.GetStartingIntent
    If in.IsInitialized And in.HasExtra("Notification_Tag") And in <> LastIntent Then
        LastIntent = in
        Dim tag As String = in.GetExtra("Notification_Tag")
        Log("User clicked notification: " & tag)
    End If
End Sub


Thanks
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
The B4J Tool is the correct one to start SENDING an Notification. Please note the words i use and their meaning. They are bold.

In Android it is the receiver module in your app where the code is which CREATES the Notification. It is the Module FirebaseMessaging in your app.
You got told to post the code that CREATES the Notification multiple times.
Also you got told to add the tag Notification_Tag to the Notification in the receiver module.
 
Upvote 0

Stevenindonesia

Member
Licensed User
DonManfred.

After a couple of studies, I added extra data - Notification_Tag in the firebase send.

Now i manage to capture the intend.

Thank you for your help.
 
Upvote 0
Top