Android Question Tracking user location

ttsolution

Member
Licensed User
Longtime User
Hi All,

I used below code in a service to tracking user location every 5 minutes. After 5-10 times works well the FusedLocationProvider1_LocationChanged event not fire any more while the service repeatly start every 5 minutes as scheduled. I spent a week to search the forum to get help but still stuck.

Very much appreciate for any help

Jonh,

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

Sub Process_Globals
    Private GPS2 As GPS
    Private FusedLocationProvider1 As FusedLocationProvider
    Private LastLocation As Location
    Private Geocoder1 As Geocoder
    Private PE As PhoneEvents
    Private mBatteryLevel As Int
  
    Private Pw As PhoneWakeState
    Dim nb As Notification
    Dim Wrujob As HttpJob
End Sub

Sub Service_Create
    Try
        nb.Initialize2(nb.IMPORTANCE_MIN)
        nb.Vibrate=False
        nb.Sound=False
        nb.Light=False
        nb.Icon="blank"
        nb.SetInfo("Test","Testing","")
  
        Service.AutomaticForegroundNotification=nb
      
        Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_WHEN_NEEDED
'      
        PE.Initialize("PE")
    Catch
        Log(LastException)
    End Try
End Sub

Sub Service_Start (StartingIntent As Intent)
    Try
'        Log("Wru Service Started")
        Pw.PartialLock
      
        StartServiceAt(Me, DateTime.Now + (60*1) * 1000, True) 'will start after 5 minutes
      
        If FusedLocationProvider1.IsInitialized=False Then FusedLocationProvider1.Initialize("FusedLocationProvider1")
        If Geocoder1.IsInitialized=False Then Geocoder1.Initialize("Geocoder1")
        If GPS2.IsInitialized=False Then GPS2.Initialize("GPS2")
        If FusedLocationProvider1.IsConnected=False Then FusedLocationProvider1.Connect
    Catch
        Log(LastException)
    End Try
  
    Service.StopAutomaticForeground
End Sub

Sub Service_Destroy
    Try
        FusedLocationProvider1.Disconnect
    Catch
        Log(LastException)
    End Try
End Sub

Sub FusedLocationProvider1_ConnectionSuccess
    Try
        Dim LocationRequest1 As LocationRequest
        LocationRequest1.Initialize
        LocationRequest1.SetInterval(1)    '    18000 milliseconds = 5 minutes
        LocationRequest1.SetPriority(LocationRequest1.Priority.PRIORITY_HIGH_ACCURACY)
        LocationRequest1.SetSmallestDisplacement(0)    '    1 meter
        FusedLocationProvider1.RequestLocationUpdates(LocationRequest1)
      
        Log("ConnectionSuccess")
    Catch
        Log(LastException)
    End Try
End Sub

Sub FusedLocationProvider1_ConnectionFailed(ConnectionResult1 As Int)
    Log("ConnectionFailed")
  
    Select ConnectionResult1
        Case FusedLocationProvider1.ConnectionResult.NETWORK_ERROR
            '    a network error has occurred, this is likely to be a recoverable error
            '    so try to connect again
            FusedLocationProvider1.Connect
        Case Else
            '    TODO handle other errors
    End Select
End Sub

Sub FusedLocationProvider1_LocationChanged(Location1 As Location)
    LastLocation=Location1
  
    'Log("AccuracyValid:" & Location1.AccuracyValid & " - Accuracy:" & Location1.Accuracy)
  
    If LastLocation.AccuracyValid=True Then
        If LastLocation.Accuracy<=1000 Then
            ' Stop Listening
            FusedLocationProvider1.Disconnect
            GPS2.Stop

            ' Get Google Address
            ReseverLoc
        Else
            ' try again
            FusedLocationProvider1.Connect
        End If
    Else
        ' try again
        FusedLocationProvider1.Connect
    End If
End Sub

Sub ReseverLoc()
    Log("ReseverLoc started")
  
    If Geocoder1.IsInitialized=False Then     Geocoder1.Initialize("Geocoder1")
    Geocoder1.GetFromLocation(LastLocation.Latitude,LastLocation.Longitude, 1,Null)
End Sub

Sub Geocoder1_GeocodeDone(Results() As Address, Tag As Object)
    Dim Address1 As Address
    Dim mNumber As String=""
    Dim mStreet As String=""
    Dim mWard As String=""
    Dim mDistrict As String=""
    Dim mProvince As String=""
    Dim mFullAddress As String=""
    Dim mJSON As StringBuilder
    Dim mParameter As String=""
    Dim mUrl As String=""
  
    Log("GeocodeDone")
      
    Try
        If Results.Length>0 Then
            Address1=Results(0)
          
            mNumber =mainModule.NzStr(Address1.SubThoroughfare)
            mStreet =mainModule.NzStr(Address1.Thoroughfare)
          
            If mainModule.NzStr(Address1.Locality)<>"" Then
                mWard =mainModule.NzStr(Address1.Locality)
            Else
                mWard =mainModule.NzStr(Address1.SubLocality)
            End If
          
            mDistrict =mainModule.NzStr(Address1.SubAdminArea)
            mProvince =mainModule.NzStr(Address1.AdminArea)
          
            If mNumber.Trim.Length>0 Then mFullAddress=mNumber
          
            If mStreet.Trim.Length>0 Then
                If mFullAddress.Trim.Length=0 Then
                    mFullAddress=mStreet
                Else
                    mFullAddress=mFullAddress & " " & mStreet
                End If
            End If
          
            If mWard.Trim.Length>0 Then
                If mFullAddress.Trim.Length=0 Then
                    mFullAddress=mWard
                Else
                    mFullAddress=mFullAddress & ", " & mWard
                End If
            End If
          
            If mDistrict.Trim.Length>0 Then
                If mFullAddress.Trim.Length=0 Then
                    mFullAddress=mDistrict
                Else
                    mFullAddress=mFullAddress & ", " & mDistrict
                End If
            End If
          
            ' Send data to server
            Try
                mUrl=mainModule.getServerUrl
                If mUrl.Trim.Length>10 Then
                    mJSON.Initialize
                    mJSON.Append("[{")
                    mJSON.Append("'BatteryLevel':'" & mBatteryLevel & "',")
                    mJSON.Append("'Code':'" & Starter.gHashCode & "',")
                    mJSON.Append("'StaffId':'" & mainModule.getStaffId & "',")
                    mJSON.Append("'LAT':'" & LastLocation.Latitude & "',")
                    mJSON.Append("'LON':'" & LastLocation.Longitude & "',")
                    mJSON.Append("'Accuracy':'" & LastLocation.Accuracy & "',")
                    mJSON.Append("'Address':'" & mFullAddress & "'")
                    mJSON.Append("}]")
                    Log(mFullAddress)
              
                    mParameter="mCode=1234567890&mJSON="& mJSON.ToString
'                    Log(mUrl & " - " & mParameter)
              
                    If Wrujob.IsInitialized=False Then Wrujob.Initialize("", Me)
                    Wrujob.PostString(mUrl & "/misCoreService.asmx/MS_Update_Wru",mParameter)
                    Wait For (Wrujob) JobDone (Qjob As HttpJob)
                    If Qjob.Success Then
                        Log(Qjob.GetString)
                    Else
                        Log("Error - " & LastException)
                    End If
                End If
            Catch
                Log(LastException)
'                StartServiceAt(Me, DateTime.Now + (5*1) * 1000, True) 'will start after 5 minutes
            End Try
            Wrujob.Release
        End If
    Catch
        Log(LastException)
    End Try
  
    Service.StopAutomaticForeground
    Pw.ReleasePartialLock
  
End Sub

Sub PE_BatteryChanged(Level As Int, Scale As Int, Plugged As Boolean, Intent As Intent)
    mBatteryLevel = Level
End Sub
 
Top