Service Question...

Shortbuscandid8

New Member
Licensed User
Longtime User
I'm trying to write a program to retrieve remote battery level on a phone I SMS the message "Battery" to. I've removed all the code that checks for the string, etc. and just showing service code to intercept the SMS. This all works fine as long as the activity that loads this service is in the foreground, but if the phone is asleep or the activity is in the background, it doesn't do anything until I wake the phone and put the activity in the foreground. It seems to cache the messages. When I send more than one, it'll send back as many as I sent as soon as the phone wakes. It also will work if I hit the "connect" button on the log viewer in the IDE while the phone is asleep. I do get the icon on the taskbar so I know the service is running all the time. Any help would be appreciated. Thanks!

B4X:
'Activity Module
Sub Activity_Create(FirstTime As Boolean)
   If FirstTime Then
        StartService(BatteryLevel)
   End If
End Sub


B4X:
'Service module
Sub Process_Globals
   'These global variables will be declared once when the application starts.
   'These variables can be accessed from all modules.
        Dim n As Notification
        Dim SI As SmsInterceptor
        Dim PE As PhoneEvents
        Dim SMS1 As PhoneSms

End Sub

Sub Service_Create
   SI.Initialize2("SI", 999)
   n.Initialize
   n.Icon = "icon"
   n.Vibrate = False
   n.OnGoingEvent = True
   n.SetInfo("SMS", "Stay Alive", Main)
   Service.StartForeground(1, n) 

End Sub




Sub Service_Start (StartingIntent As Intent)
    
End Sub



Sub Service_Destroy

End Sub

Sub SI_MessageReceived (From As String, Body As String) As Boolean
   PE.Initialize("PE") 'To get Battery Stats
   Return False 'To See The SMS
End Sub

Sub PE_BatteryChanged (Level As Int, Scale As Int, Plugged As Boolean, Intent As Intent)
   SMS1.Send("XXXXXXXXXXX", "BatteryChanged: Level = " & Level & ", Scale = " & Scale & ", Plugged = " & Plugged)
End Sub
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
You cannot acquire a partial lock forever. It will prevent the device from sleeping.

See this link: Intent Filters - Intercepting SMS messages in the background
This will however not help you with getting the battery level. For that you need to use StartServiceAt and listen for the battery intent (which should be sent right after you initialize PhoneEvents) and save the value in a file.
 
Upvote 0
Top