Android Question Run GPS Tracker Service in Sleep Mode

AndroidMadhu

Active Member
Licensed User
Hello,
I am trying to develop GPS Tracker Service, and my app is running fine when the App is Alive.
But when the App is in Sleep mode or in background the GPS tracker is not working and not providing any lat/long after some time.

The below link I am following but it is not working. After 1 minute of sleep the GPS tracking stop sending lat/long.

https://www.b4x.com/android/forum/threads/continous-background-gps-tracking.110628/#content

https://www.b4x.com/android/forum/threads/background-location-tracking.99873/

The below is the code block:
B4X:
 Sub Service_Create
Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_NEVER 'we are handling it ourselves
GPS.Initialize("gps")
lock.PartialLock
End Sub

Sub Service_Start (StartingIntent As Intent)
Service.StartForeground(nid, CreateNotification("..."))
StartServiceAt(Me, DateTime.Now + 30 * DateTime.TicksPerMinute, True)
Track
End Sub

B4X:
 Public Sub Track
If Tracking Then Return
If Main.rp.Check(Main.rp.PERMISSION_ACCESS_FINE_LOCATION) = False Then
Log("No permission")
Return
End If
GPS.Start(0, 0)
Tracking = True
End Sub

Sub GPS_LocationChanged (Location1 As Location)
Dim strLoc As String
If DateTime.Now > LastUpdateTime + 10 * DateTime.TicksPerSecond Then
Dim n As Notification = CreateNotification($"$2.5{Location1.Latitude} / $2.5{Location1.Longitude}"$)
n.Notify(nid)
LastUpdateTime = DateTime.Now
gpslat = Location1.Latitude
gpslong = Location1.Longitude
If gpslat>0 And gpslong>0 Then
'CallSubDelayed2(Main,"Update_Location",Location1)
Dim bc As ByteConverter

strLoc=gpslat & "/" &gpslong '& qrActivity.sessionId ''''"newloc_" &
If Starter.mqtt.Connected Then

Starter.mqtt.Publish("driver_" & qrActivity.sessionId,bc.StringToBytes(strLoc ,"UTF8"))

Else
Log("MQTT not connected")
End If
ToastMessageShow(gpslat & "/" &gpslong,True)
End If
End If
End Sub

Please advice on this.....

Thanks
 

TILogistic

Expert
Licensed User
Longtime User
note:

see:

B4X:
Sub Service_Start (StartingIntent As Intent)
    Service.StartForeground(nid, CreateNotification("..."))
    StartServiceAt(Me, DateTime.Now + 30 * DateTime.TicksPerMinute, True)
    Track
End Sub

this is where the track restarts, check its duration
 
Last edited:
Upvote 0

TILogistic

Expert
Licensed User
Longtime User
post an example of your project to review and know where you have the problem,
Indicate which version of android to use,
 
Upvote 0

AndroidMadhu

Active Member
Licensed User
Hello,
@oparra ... Please find the below code for your reference.
GPS is stop working when the App is at background.
I am using Android 10 and B4A version 10.2.

Main Activity
B4X:
#Region  Project Attributes
    #ApplicationLabel: gps test1
    #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.
    Private xui As XUI
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
End Sub

Sub Activity_Create(FirstTime As Boolean)
    If Not(Tracker.rp.Check(Tracker.rp.PERMISSION_ACCESS_FINE_LOCATION)) Then
        Tracker.rp.CheckAndRequest(Tracker.rp.PERMISSION_ACCESS_FINE_LOCATION)
        Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
    End If
    Activity.LoadLayout("Layout")
    StartService(Tracker)
End Sub

Sub Activity_Resume
    
End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub Button1_Click
    xui.MsgboxAsync("Hello world!", "B4X")
End Sub

Sub Update_location(loc As Location)
    ToastMessageShow(loc.Latitude & "/" & loc.Longitude,True)
End Sub

From Tracker Service
B4X:
#Region  Service Attributes
    #StartAtBoot: True
#End Region
#StartCommandReturnValue: android.app.Service.START_STICKY

Sub Process_Globals
    Private nid As Int = 1
    Private GPS As GPS
    Private Tracking As Boolean
    Private LastUpdateTime As Long
    Private lock As PhoneWakeState
    Dim gpslong, gpslat As Double
    Dim tmrTracker As Timer
    Dim counter As Int
    Dim rp As RuntimePermissions
    Dim LastLocation As Location
    
End Sub

Sub Service_Create
    Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_NEVER 'we are handling it ourselves
    GPS.Initialize("gps")
    lock.PartialLock
    Try
        tmrTracker.Initialize("Timer1",1000)
        
    Catch
        Log(LastException)
    End Try
    tmrTracker.Enabled=True
    
End Sub

Sub Service_Start (StartingIntent As Intent)
    Service.StartForeground(nid, CreateNotification("..."))
    StartServiceAt(Me, DateTime.Now + 30 * DateTime.TicksPerMinute, True)
    Log("Tracker Service start")
    Track
End Sub

Public Sub Track
    If Tracking Then Return
    If rp.Check(rp.PERMISSION_ACCESS_FINE_LOCATION) = False Then
        Log("No permission")
        Return
    End If
    GPS.Start(22, 88)
    'LastUpdateTime = DateTime.Now
    Tracking = True
End Sub

Sub GPS_LocationChanged (Location1 As Location)
    Dim strLoc As String
    If DateTime.Now > LastUpdateTime + 10 * DateTime.TicksPerSecond Then
    ToastMessageShow(Location1.Latitude & "/" & Location1.Longitude,True)
    LastLocation=Location1
    'GPS.Start(LastLocation.Latitude,LastLocation.Longitude)
    LastUpdateTime = DateTime.Now
    
    Else
    ToastMessageShow("else 1",True)
            
    End If
End Sub

Sub CreateNotification (Body As String) As Notification
    Dim notification As Notification
    notification.Initialize2(notification.IMPORTANCE_LOW)
    notification.Icon = "icon"
    notification.SetInfo("Tracking location", Body, Main)
    Return notification
End Sub

Sub Service_Destroy
    ToastMessageShow("Service Destroy",True)
    If Tracking Then
        GPS.Stop
    End If
    Tracking = False
    lock.ReleasePartialLock
End Sub
private Sub RunCounter
    
    Try
        Dim IsP_Main As Boolean
        IsP_Main=IsPaused(Main)
        If IsP_Main  Then
            counter = counter + 1
            If counter = 6 Then
                counter=0
                'GPS.Start(LastLocation.Latitude,LastLocation.Longitude)
            End If
        Else
            counter = 0
        End If
    
    Catch
        Log("RunCounter " & LastException)
    End Try
    
End Sub

Sub timer1_tick
    
    Try
        RunCounter
        'Log("Counter=" & counter & " " & DateUtils.TicksToString(DateTime.Now))
    Catch
        Log("timer1_tick " & LastException)
    End Try
    
    
End Sub

From Starter Service
B4X:
#Region  Service Attributes
    #StartAtBoot: False
    #ExcludeFromLibrary: True
#End Region

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 Service_Create
    'This is the program entry point.
    'This is a good place to load resources that are not specific to a single activity.

End Sub

Sub Service_Start (StartingIntent As Intent)
    Service.StopAutomaticForeground 'Starter service can start in the foreground state in some edge cases.
End Sub

Sub Service_TaskRemoved
    'This event will be raised when the user removes the app from the recent apps list.
End Sub

'Return true to allow the OS default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
    Return True
End Sub

Sub Service_Destroy

End Sub

Please advice on this please.....

Thanks
 
Upvote 0

TILogistic

Expert
Licensed User
Longtime User
use this demo and see what happens in the notification bar.

test away from home to detect GPS positions

Don't use a timer
don't use ToastMessageShow


Version 10.2


1603887064640.png


B4X:
'This code will be applied to the manifest file during compilation.
'You do not need to modify it in most cases.
'See this link for for more information: https://www.b4x.com/forum/showthread.php?p=78136
AddManifestText(
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="29"/>
<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.DarkTheme)
'End of default text.

SetServiceAttribute(Tracker, android:foregroundServiceType, "location")



1604057249361.png
 

Attachments

  • MyLocationDemo.zip
    8.9 KB · Views: 213
Upvote 0

TILogistic

Expert
Licensed User
Longtime User
tips:
StartServiceAt (Service As Object, Time As Long, DuringSleep As Boolean)
Schedules the given service to start at the given time.
Service - The service module. Pass Me when calling from a service module that schedules itself.
Time - The time to start the service. If this time has already past the service will be started now.
The actual delivery time might change to reduce battery usage. Use StartServiceAtExact if the exact time is important.
DuringSleep - Whether to start the service when the device is sleeping. If set to false and the device is sleeping
at the specified time, the service will be started when the device wakes up.
Setting DuringSleep to True can have a large impact on the battery usage.
StartServiceAt can be used to schedule a repeating task. You should call it under Service_Start to schedule the next task.
This call cancels previous scheduled tasks (for the same service).
Example:
StartServiceAt(SQLService, DateTime.Now + 30 * 1000, false) 'will start after 30 seconds.
 
Upvote 0

TILogistic

Expert
Licensed User
Longtime User
I recommend that you see this type of development, it solves several problems with background processes:


 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
Service.StopAutomaticForeground 'Starter service can start in the foreground state in some edge cases.
Are you sure you are not killing your app by doing this in the Starter service?

What is the purpose of the Timer?
 
Upvote 0

TILogistic

Expert
Licensed User
Longtime User
Are you sure you are not killing your app by doing this in the Starter service?

What is the purpose of the Timer?

What he said is true.

AndroidMadhu:

see the demo to understand the use and behavior of background processes
 
Last edited:
Upvote 0

kohle

Active Member
Licensed User
Longtime User
sometimes it depends on the phone and (modified) Android. In my case, my Huawai P30 pro puts after 15min a background service on hold (like on a stack) when its in
standyby mode. When I awake my phone, the processes are triggered on after another.
I used an old Samsung S4/S5 mini, connected to usb in my car as gps tracker. This worked without problems.
 
Upvote 0
Top