Get LocationUpdates in background service continuously

前端 未结 2 1828
后悔当初
后悔当初 2021-02-06 14:17

I am working on application which requires to fetch location updates continuously in background service. I have used background sticky service with which it is working. But serv

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-06 14:44

    You can use fused location provider to get the location of the device at regular intervals. There is a direct approach to request periodic updates from the fused location provider. The accuracy of the location is determined by the providers, the location permissions you've requested, and the options you set in the location request.

    Request location updates

    Before requesting location updates, your app must connect to location services and make a location request. The lesson on Changing Location Settings shows you how to do this. Once a location request is in place you can start the regular updates by calling requestLocationUpdates().

    Depending on the form of the request, the fused location provider either invokes the LocationCallback.onLocationChanged() callback method and passes it a list of Location objects, or issues a PendingIntent that contains the location in its extended data. The accuracy and frequency of the updates are affected by the location permissions you've requested and the options you set in the location request object.

    This lesson shows you how to get the update using the LocationCallback callback approach. Call requestLocationUpdates(), passing it your instance of the LocationRequest object, and a LocationCallback. Define a startLocationUpdates() method as shown in the following code sample:

    @Override
    protected void onResume() {
        super.onResume();
        if (mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }
    
    private void startLocationUpdates() {
        mFusedLocationClient.requestLocationUpdates(mLocationRequest,
                mLocationCallback,
                null /* Looper */);
    }
    

    Read Official Documentation here for detailed description.

    Hope this helps.

提交回复
热议问题