Android Question Reading sms in the background

Pesciolina

Member
Licensed User
Hi,
I used this code that works very well even when the App is in the backgroud, the only problem is that if the app is not open when a text message arrives, how can I remove this function?
Thanks
Marco

B4X:
#Region  Service Attributes
    #StartAtBoot: False
    
#End Region
'Service module
Sub Process_Globals
    Type Message (Address As String, Body As String)
    
End Sub
Sub Service_Create
    
End Sub

Sub Service_Start(startingIntent As Intent)
    If startingIntent.Action = "android.provider.Telephony.SMS_RECEIVED" Then
        Dim messages() As Message
        Dim Messaggio() As String
        Dim Stato As String   
        messages = ParseSmsIntent(startingIntent)
        For i = 0 To messages.Length - 1
            Log(messages(i))
            
            Messaggio=Regex.Split ("?",messages(i).Body)
            
            
        Next
    End If
    Service.StopAutomaticForeground
End Sub

'Parses an SMS intent and returns an array of messages
Sub ParseSmsIntent (in As Intent) As Message()
    Dim messages() As Message
    
    If in.HasExtra("pdus") = False Then Return messages
    Dim pdus() As Object
    Dim r As Reflector
    pdus = in.GetExtra("pdus")
    If pdus.Length > 0 Then
        Dim messages(pdus.Length) As Message
        For i = 0 To pdus.Length - 1
            r.Target = r.RunStaticMethod("android.telephony.SmsMessage", "createFromPdu", _
            Array As Object(pdus(i)), Array As String("[B"))
            messages(i).Body = r.RunMethod("getMessageBody")
            messages(i).Address = r.RunMethod("getOriginatingAddress")       
            
        Next
    End If
    Return messages
End Sub
Manifest S1:
AddPermission(android.permission.RECEIVE_SMS)
AddReceiverText(s1,
<intent-filter>
    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>)
 

svanneste

Member
Licensed User
Hi,
Perhaps could you check the status of the app or by simply checking if IsPaused(Main) in Service_Start before parsing
or another idea could be to store the state of the app from Activity_Pause in a global variable in the Starter service ?
 
Upvote 0

Pesciolina

Member
Licensed User
i created a public variable that i put to true when i open the app, it seems to work i hope it's correct
B4X:
Sub Service_Create
    
    If Starter.AppOn = False Then
        
        ExitApplication
    End If
    
End Sub
 
Upvote 0

kisoft

Well-Known Member
Licensed User
Try this, don't use exapp, it's a bug.
B4X:
Sub Service_Create
    
    Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_ALWAYS
    
End Sub
 
Upvote 0
Top