Android Question 401 error in push solution for android

oscarv

Member
Good afternoon, with the modification that was made to send push messages on Android, I get a 401 error.


Registration connected to: 42005b5b97286659
--------- beginning of main
--------- system start
***Service (start) Create***
** Start of service (boot) **
**Activity (main) Create (first time)**
###########################The file exists
/data/user/0/makoa.rosasarone/files/*********************************************.json
Token could not be created
**Activity summary (main)**
sending message to uninitialized activity queue (submitjob)
***Receiver (httputils2service) Receive (first time)***
**Activity (main) Pause, UserClosed = false **
sending message to queue (sleep)
***Service (startup) Create***
** Start of service (boot) **
**Activity (main) Create (first time)**
###########################The file exists
/data/user/0/makoa.rosasarone/files/***********************************************.json
Token could not be created
**Activity summary (main)**
***Receiver (httputils2service) Receive (first time)***
Response error. Reason: , Response: {
"mistake": {
"code": 401,
"message": "The request is missing required authentication credentials. An OAuth 2 access token, login cookie, or other valid authentication credential was expected. See https://developers.google.com/identity/ login/web/devconsole-project.",
"status": "UNAUTHENTICATED",
"details": [
{
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "MISSING_CREDENTIALS",
"domain": "googleapis.com",
"metadata": {
"method": "google.firebase.fcm.v1.FcmService.SendMessage",
"service": "fcm.googleapis.com"
}
}
]
}

}

I have installed and verified that the access exists in DirInternal and I have even tried using it from DirAssets. I know it's something simple, but I can't find what else to do.
Thanks in advance
 

oscarv

Member
Good afternoon :


this is the create routine



B4X:
Sub Process_Globals
    Private Const ProjectId As String = "******************" 'change
    Private acceso As String = "*********************************.json" 'change
    Private ServiceAccountFilePath As String=File.DirInternal&"/*************************************************************.json"
    Private Token As String

B4X:
Sub Activity_Create (FirstTime As Boolean)
    Activity.LoadLayout("menu")
    icono=LoadBitmap(File.DirAssets, "icovivo.png")
    icono2=LoadBitmap(File.DirAssets, "icovivo2.png")
    icono3=LoadBitmap(File.DirAssets, "icocale.webp")
    icono4=LoadBitmap(File.DirAssets, "icocale2.webp")
    If AH_CheckInternet.Check_AirplaneMode=True Then
        mensaje.Bitmap=LoadBitmap(File.DirAssets,"avion.webp")
        Panelmensaje.Visible=True
        Sleep(3000)
        Panelmensaje.Visible=False
        Activity.Finish
    End If
    If AH_CheckInternet.Check_NetworkConnection=False And AH_CheckInternet.Check_NetworkRoaming=False Then
        mensaje.Bitmap=LoadBitmap(File.DirAssets,"wifi.webp")
        Panelmensaje.Visible=True
        Sleep(3000)
        Panelmensaje.Visible=False
        Activity.Finish
    End If
    titulo.SetGif(File.DirAssets, "rosagif.gif")
    titulo.Base_Resize(60%x,9.2%y)
    logo.Bitmap=LoadBitmap(File.DirAssets,"logors.webp")
    TabHost1.AddTabWithIcon("",icono2,icono, "envivo.bal")
    TabHost1.AddTabWithIcon("",icono4,icono3, "notifica.bal")
    lhora.Visible=False
    lmin.Visible=False
    listhor.Visible=False
    listmin.Visible=False
    Listdia.Visible=False
    Listmes.Visible=False
    Listano.Visible=False
    amn.Checked=False
    pmn.Checked=False
    If File.Exists(File.dirinternal,"envivo.txt")=False Then
        File.Copy(File.DirAssets,"envivo.txt",File.dirinternal,"envivo.txt")
    End If
    listavivo = File.ReadList(File.dirinternal, "envivo.txt")
    If listavivo.Get(0)="n" Then
        hore.Text="00"
        mine.Text="00"
        am.Checked=False
        pm.Checked=False
    Else
        Dim horatext As String
        horatext=listavivo.Get(0)
        Select horatext.SubString2(6,8)
            Case "13","14","15","16","17","18","20","21","22","23"
                Dim he As Int
                he=horatext.SubString2(6,8)-12
                hore.Text="0"&he
                pm.Checked=True
                am.Checked=False
            Case "12"
                hore.Text=horatext.SubString2(6,8)
                pm.Checked=True
                am.Checked=False
            Case "01","02","03","04","05","06","07","08","09","10","11"
                hore.Text=horatext.SubString2(6,8)
                pm.Checked=False
                am.Checked=True
            Case "24"
                hore.Text=horatext.SubString2(6,8)-12
                pm.Checked=False
                am.Checked=True
        End Select
        mine.Text=horatext.SubString(9)
    End If
    If listavivo.Get(1)<>"n" Then enle.Text=listavivo.Get(1) Else enle.Text=""
    
'************************************************************************   
    
    If FirstTime Then
        DisableStrictMode
    End If
    
    File.Copy(File.DirAssets, acceso, File.DirInternal, acceso)
    
    
    
    If File.Exists(File.DirInternal, acceso) Then
        Log("#########################File Exists")
    End If
        
    Send("rosachurch", "title", "Initial run message")
    
'********************************************************   
    
    Do While sale=0
        Sleep(0)
    Loop
    ExitApplication
End Sub

B4X:
Private Sub GetTokenValue (FilePath As String) As String

    Try
        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)
    Catch
        Log("Token Failed to be created")
        Return ""
    End Try
End Sub

B4X:
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)
    message.Put("android", CreateMap("priority": "high"))
    Dim jg As JSONGenerator
    jg.Initialize(CreateMap("message": message))
    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 DisableStrictMode
    Dim jo As JavaObject
    jo.InitializeStatic("android.os.Build.VERSION")
    If jo.GetField("SDK_INT") > 9 Then
        Dim policy As JavaObject
        policy = policy.InitializeNewInstance("android.os.StrictMode.ThreadPolicy.Builder", Null)
        policy = policy.RunMethodJO("permitAll", Null).RunMethodJO("build", Null)
        Dim sm As JavaObject
        sm.InitializeStatic("android.os.StrictMode").RunMethod("setThreadPolicy", Array(policy))
    End If
End Sub




Generate the json file according to this step without problem :

Project settings - Service accounts - Generate new private sign key. The browser will download a json file. This file includes a private key that gives access to your firebase account. Keep it secured.


This is the manifest document

B4X:
AddManifestText(
<uses-sdk android:minSdkVersion="20" android:targetSdkVersion="34"/>
<uses-feature android:name="android.hardware.location.gps"/>
<supports-screens android:largeScreens="true"
    android:normalScreens="true"
    android:smallScreens="true"
    android:anyDensity="true"/>)
 
SetApplicationAttribute(android:icon, "@drawable/icon")
SetApplicationAttribute(android:label, "$LABEL$")
CreateResourceFromFile(Macro, Themes.LightTheme)
CreateResourceFromFile(Macro, FirebaseAnalytics.Firebase)
CreateResourceFromFile(Macro, FirebaseAnalytics.FirebaseAnalytics)
CreateResourceFromFile(Macro, FirebaseAnalytics.GooglePlayBase)
CreateResourceFromFile(Macro, FirebaseAnalytics.Firebase)
CreateResourceFromFile(Macro, FirebaseNotifications.FirebaseNotifications)
CreateResourceFromFile(Macro, FirebaseAuth.FirebaseAuth)


Thanks in advance!!
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…