目录

Developing the Fused Location Service

Overview

The Android SDK provides a solution for developers to obtain device location information. It is intended for developers who have Android programming experience and understand object-oriented programming.

By default, the fused location function uses the WGS84 coordinate system for the returned locations. You can use the setCoordinateType method in LocationRequest to set the used coordinate system. If the coordinate type is set to GCJ02, the location information after coordinate conversion needs to be obtained from the HWLocation object.

Assigning App Permissions

  1. Declare the required permissions in the AndroidManifest.xml file. The Android OS provides two location permissions: ACCESS_COARSE_LOCATION (approximate location permission) and ACCESS_FINE_LOCATION (precise location permission).
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  2. (Optional) If your app needs to continuously locate the device when it runs in the background in Android 10 or later, declare the ACCESS_BACKGROUND_LOCATION permission in the AndroidManifest.xml file.
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
  3. Dynamically apply for related location permissions (according to requirements for dangerous permissions in Android 6.0 or later).
    Java
    // Dynamically apply for required permissions if the API level is 28 or lower.
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
        Log.i(TAG, "android sdk <= 28 Q");
        if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            String[] strings =
                {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
            ActivityCompat.requestPermissions(this, strings, 1);
        }
    } else {
        // Dynamically apply for the android.permission.ACCESS_BACKGROUND_LOCATION permission in addition to the preceding permissions if the API level is higher than 28. 
        if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                "android.permission.ACCESS_BACKGROUND_LOCATION") != PackageManager.PERMISSION_GRANTED) {
            String[] strings = {android.Manifest.permission.ACCESS_FINE_LOCATION,
                android.Manifest.permission.ACCESS_COARSE_LOCATION,
                "android.permission.ACCESS_BACKGROUND_LOCATION"};
            ActivityCompat.requestPermissions(this, strings, 2);
        }
    }
    Kotlin
    // Dynamically apply for required permissions if the API level is 28 or smaller.
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
        Log.i(TAG, "android sdk <= 28 Q")
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            val strings = arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
            ActivityCompat.requestPermissions(this, strings, 1)
        }
    } else {
        // Dynamically apply for required permissions if the API level is greater than 28. The android.permission.ACCESS_BACKGROUND_LOCATION permission is required.
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                this,
                "android.permission.ACCESS_BACKGROUND_LOCATION"
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            val strings = arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                "android.permission.ACCESS_BACKGROUND_LOCATION"
            )
            ActivityCompat.requestPermissions(this, strings, 2)
        }
    }
  • ACCESS_COARSE_LOCATION: approximate location permission, which provides location information accurate to the city block level.
  • ACCESS_FINE_LOCATION: precise location permission, which allows your app to obtain the user location which is more accurate than that obtained based on the ACCESS_COARSE_LOCATION permission.
  • ACCESS_BACKGROUND_LOCATION: background location permission, which allows your app to obtain the user location when it runs in the background in Android 10 (API level: 29). In Android 10 or later, this permission is a dangerous permission and needs to be dynamically applied for. In versions earlier than Android 10, your app can obtain the user location regardless of whether it runs in the foreground or background, as long as it is assigned the ACCESS_COARSE_LOCATION permission.
  • In Android 11 (API level: 30) or later, you cannot dynamically apply for the above three permissions at the same time. You can apply for the ACCESS_BACKGROUND_LOCATION permission only after the ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION permissions are granted.

Checking the Device Location Settings

Device location settings will directly affect the location result. For example, if the location function is disabled on a device, your app cannot obtain the device location. Therefore, it is recommended that your app check whether the location function is enabled on a device before continuously obtaining the device location.

  1. Call the getSettingsClient() method to obtain a SettingsClient instance.
    Java
    SettingsClient settingsClient = LocationServices.getSettingsClient(this);
    Kotlin
    var settingsClient = LocationServices.getSettingsClient(this)
  2. Call checkLocationSettings() to check the device location settings.
    Java
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
    LocationRequest mLocationRequest = new LocationRequest();
    builder.addLocationRequest(mLocationRequest);
    LocationSettingsRequest locationSettingsRequest = builder.build();
    // Check the device location settings.
    settingsClient.checkLocationSettings(locationSettingsRequest)
        // Define the listener for success in calling the API for checking device location settings.
        .addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
            @Override
            public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                LocationSettingsStates locationSettingsStates =
                    locationSettingsResponse.getLocationSettingsStates();
                StringBuilder stringBuilder = new StringBuilder();
                // Check whether the location function is enabled. 
                stringBuilder.append(",\nisLocationUsable=")
                    .append(locationSettingsStates.isLocationUsable());
                // Check whether HMS Core (APK) is available. 
                stringBuilder.append(",\nisHMSLocationUsable=")
                    .append(locationSettingsStates.isHMSLocationUsable());
                Log.i(TAG, "checkLocationSetting onComplete:" + stringBuilder.toString());
            }
        })
        // Define callback for failure in checking the device location settings.
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                Log.i(TAG, "checkLocationSetting onFailure:" + e.getMessage());
            }
        });
    Kotlin
    val builder = LocationSettingsRequest.Builder()
    var mLocationRequest = LocationRequest()
    
    builder.addLocationRequest(mLocationRequest)
    val locationSettingsRequest = builder.build()
    // Check the device location settings.
    settingsClient.checkLocationSettings(locationSettingsRequest) 
        // Define the listener for success in calling the API for checking device location settings.
        .addOnSuccessListener(OnSuccessListener { locationSettingsResponse ->
            val locationSettingsStates = locationSettingsResponse.locationSettingsStates
            val stringBuilder = StringBuilder()
            // Check whether the location function is enabled. 
            stringBuilder.append("isLocationUsable=")
                .append(locationSettingsStates.isLocationUsable)
            // Check whether HMS Core (APK) is available. 
            stringBuilder.append(",\nisHMSLocationUsable=")
                .append(locationSettingsStates.isHMSLocationUsable)
            Log.i(TAG, "checkLocationSetting onComplete:$stringBuilder")
        }) 
        // Define callback for failure in checking the device location settings.
        .addOnFailureListener(OnFailureListener { e ->
            Log.i(TAG, "checkLocationSetting onFailure:" + e.message)
        })

On non-Huawei devices, only the location switch status is returned. You can prompt users to turn on the location switch based on the switch status. On Huawei devices, a popup can be opened for users to turn on the location switch quickly.

Initializing the Location

Declare a FusedLocationProviderClient object in the main thread and pass parameters of the Context or Activity type.

Java
// Define a fusedLocationProviderClient object.
private FusedLocationProviderClient fusedLocationProviderClient; 
// Instantiate the fusedLocationProviderClient object.
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this); 
Kotlin
// Define a fusedLocationProviderClient object.
private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
// Instantiate the fusedLocationProviderClient object.
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)

Selecting a Location Mode

The Location SDK provides the single location, continuous location, and background location capabilities. You can select a proper location mode based on your service scenario. The methods for setting different location modes are as follows:

[h2]Single Location

Java
LocationRequest mLocationRequest = new LocationRequest();
// Set the location type.
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the number of location updates to 1.
mLocationRequest.setNumUpdates(1);
Kotlin
val mLocationRequest = LocationRequest()
// Set the location type.
mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
// Set the number of location updates to 1.
mLocationRequest.numUpdates = 1

[h2]Continuous Location

Java
LocationRequest mLocationRequest = new LocationRequest();
// Set the location update interval, in milliseconds.
mLocationRequest.setInterval(10000);
// Set the location type.
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
Kotlin
val mLocationRequest = LocationRequest()
// Set the location update interval, in milliseconds.
mLocationRequest.interval = 10000
// Set the location type.
mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
Table 1 Core methods in LocationRequest

Method

Parameter

Return Value

Method Description

Default Value

setPriority(int priority)

If the GNSS location is requested, set priority to 100. If the network location is requested, set priority to 102 or 104. If the location only needs to be passively received instead of being proactively requested, set priority to 105. If high-precision location is requested, set the priority to 200.

LocationRequest object

Sets the location type.

PRIORITY_BALANCED_POWER_ACCURACY

setInterval(long millis)

If the value is 50000, the app will receive a location update every 50 seconds.

LocationRequest object

Sets the interval for requesting location updates.

3600000

setNumUpdates(int numUpdates)

If the value is 3, the app will receive only three location updates.

LocationRequest object

Sets the number of requested location updates.

Integer.MAX_VALUE

setFastestInterval(long millis)

If another app initiates a location request, the location is also reported to that app at the interval specified in fastestInterval.

LocationRequest object

Sets the fastest interval for requesting location updates.

600000

isFastestIntervalExplicitlySet()

null

boolean

Checks whether the fastest request interval is used.

If yes, the value true is returned. Otherwise, the value false is returned.

setExpirationTime(long millis)

If the location update requesting needs to be stopped 200 seconds later, the request expiration time should equal to the return result of SystemClock.elapsedRealtime() plus 200,000.

LocationRequest object

Sets the request expiration time.

Long.MAX_VALUE

setExpirationDuration(long millis)

Different from expirationTime, the ExpirationDuration parameter is irrelevant to the boot time. If the location update requesting needs to be stopped 200 seconds later, the request expiration duration should be 200000.

LocationRequest object

Sets the request expiration duration.

Long.MAX_VALUE

setSmallestDisplacement(float smallestDisplacement)

If the displacement between two locations is greater than or equal to the specified parameter value, a location update will be sent to the app.

LocationRequest object

Sets the smallest displacement for sending a location update.

0

setMaxWaitTime(long millis)

The parameter value is in milliseconds.

When the setting takes effect, the time specified by maxWaitTime will be used as the location update period. After the location update time is reached, locations in the period will be returned to the app at a time.

LocationRequest object

Sets the maximum waiting time for location updates.

0

setNeedAddress(boolean needAddress)

The needAddress parameter is of the Boolean type. The value true indicates that the address needs to be returned, and the value false indicates that the address does not need to be returned.

LocationRequest object

Sets whether the address needs to be returned.

false

setLanguage(String language)

The value is a two-letter code complying with the ISO 639-1 standard. For example, en indicates English. By default, this parameter is left empty. Currently, the options include only en and zh.

LocationRequest object

Sets the language.

This parameter is left empty by default.

setCountryCode(String countryCode)

The value is a two-letter code complying with the ISO 3166-1 standard. By default, this parameter is left empty. Currently, the options include only EN and CN.

LocationRequest object

Sets the country/region code.

This parameter is left empty by default.

setCoordinateType(int coordinateType)

If COORDINATE_TYPE_WGS84 is passed to the method, the WGS84 coordinate type will be used.

If COORDINATE_TYPE_GCJ02 is passed to the method, the GCJ02 coordinate type will be used.

LocationRequest object

Sets the coordinate type.

By default, COORDINATE_TYPE_WGS84 is passed to the method, indicating to use the WGS84 coordinate type.

[h2]Background Location

  1. Declare the background location permission in AndroidManifest.xml.
    <service        
    android:name="com.huawei.location.service.BackGroundService"        
    android:foregroundServiceType="location" /> 
  2. (Optional) Declare the FOREGROUND_SERVICE permission in the AndroidManifest.xml file in Android 9 or later to ensure that the background location permission can be properly used.
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
  3. Call the enableBackgroundLocation() method and pass the service notification to enable the background location mode.
    Java
    Notification.Builder builder;
    Notification mNotification;
    int notificationId = 1;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        String channelId = context.getPackageName();
        NotificationChannel notificationChannel =
            new NotificationChannel(channelId, "LOCATION", NotificationManager.IMPORTANCE_LOW);
        notificationManager.createNotificationChannel(notificationChannel);
        builder = new Notification.Builder(context, channelId);
    } else {
        builder = new Notification.Builder(context);
    }
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        mNotification = builder.build();
    } else {
        mNotification = builder.getNotification();
    }
    fusedLocationProviderClient.enableBackgroundLocation(notificationId,mNotification);        
    Kotlin
    val builder: Notification.Builder
    val mNotification: Notification
    var notificationId = 1
    builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val notificationManager =
            context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val channelId = context.packageName
        val notificationChannel =
            NotificationChannel(channelId, "LOCATION", NotificationManager.IMPORTANCE_LOW)
        notificationManager.createNotificationChannel(notificationChannel)
        Notification.Builder(context, channelId)
    } else {
        Notification.Builder(context)
    }
    mNotification = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        builder.build()
    } else {
        builder.notification
    }
    fusedLocationProviderClient.enableBackgroundLocation(notificationId,mNotification)
    • This method is a new method in Location Kit 6.0.0 and supported only in scenarios where HMS Core (APK) is not preloaded. It enables your app to continuously request device locations on some phone models when your app runs in the background or the device screen is turned off.
    • For details about the code implementation, please refer to content in the code repository.

Requesting Location Updates

  1. Define the location update callback.
    Java
    LocationCallback mLocationCallback;        
    mLocationCallback = new LocationCallback() {        
        @Override        
        public void onLocationResult(LocationResult locationResult) {        
            if (locationResult != null) {        
                // TODO: Process the location callback result.
            }        
        }        
    };
    Kotlin
    val mLocationCallback: LocationCallback
    mLocationCallback = object : LocationCallback() {
        override fun onLocationResult(locationResult: LocationResult) {
            if (locationResult != null) {
                // TODO: Process the location callback result.
            }
        }
    }
  2. Call requestLocationUpdates() to request location updates.
    Java
    fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper())        
        .addOnSuccessListener(new OnSuccessListener<Void>() {        
            @Override        
            public void onSuccess(Void aVoid) {        
                // TODO: Define callback for API call success.
            }        
        })
        .addOnFailureListener(new OnFailureListener() {        
            @Override        
            public void onFailure(Exception e) {        
               // TODO: Define callback for API call failure.
            }        
        });
    Kotlin
    fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper())
        .addOnSuccessListener {
            // TODO: Define callback for API call success.
        }
        .addOnFailureListener {
            // TODO: Define callback for API call failure.
        }

    If the method is called successfully but no device location is obtained, please refer to After integrating the Location SDK, my app called the API successfully but failed to obtain the location on phones or Huawei tablets. Why?.

Stopping Requesting Location Updates

(Optional) If the background location mode is used, disable it before stopping requesting location updates.
Java
fusedLocationProviderClient.disableBackgroundLocation();        
Kotlin
fusedLocationProviderClient.disableBackgroundLocation()
Call removeLocationUpdates() to stop requesting location updates.
Java
// Note: When you stop requesting location updates, mLocationCallback must be the same object as LocationCallback passed to the requestLocationUpdates method.
fusedLocationProviderClient.removeLocationUpdates(mLocationCallback)        
    // Define callback for success in stopping requesting location updates.
    .addOnSuccessListener(new OnSuccessListener<Void>() {        
        @Override        
        public void onSuccess(Void aVoid) {      
           // TODO: Define callback for success in stopping requesting location updates.
        }        
    })
    // Define callback for failure in stopping requesting location updates.
    .addOnFailureListener(new OnFailureListener() {        
        @Override        
        public void onFailure(Exception e) {      
           // TODO: Define callback for failure in stopping requesting location updates.
        }        
    });
Kotlin
// Note: When you stop requesting location updates, mLocationCallback must be the same object as LocationCallback passed to the requestLocationUpdates method.
fusedLocationProviderClient.removeLocationUpdates(mLocationCallback) 
    // Define callback for success in stopping requesting location updates.
    .addOnSuccessListener {
        // TODO: Define callback for success in stopping requesting location updates.
    } 
    // Define callback for failure in stopping requesting location updates.
    .addOnFailureListener {
        // TODO: Define callback for failure in stopping requesting location updates.
    }

Obtaining the Last Known Location

You can call the getLastLocation() method to obtain the last known location of a device. In most cases, the last known location is the current location of the device. The sample code is as follows:
Java
// Obtain the last known location.
Task<Location> task = fusedLocationProviderClient.getLastLocation()        
    // Define callback for success in obtaining the last known location. 
    .addOnSuccessListener(new OnSuccessListener<Location>() {        
        @Override      
        public void onSuccess(Location location) {        
            if (location == null) {        
               return;        
            }        
            // TODO: Define logic for processing the Location object upon success. 
        }        
    })
    // Define callback for failure in obtaining the last known location. 
    .addOnFailureListener(new OnFailureListener() {        
        @Override        
        public void onFailure(Exception e) {        
           // TODO: Define callback for API call failure.
        }        
    });
Kotlin
val lastLocation =
    fusedLocationProviderClient.lastLocation
lastLocation.addOnSuccessListener(OnSuccessListener { location ->
    if (location == null) {
        return@OnSuccessListener
    }
    // TODO: Define logic for processing the Location object upon success. 
    return@OnSuccessListener
})
    // Define callback for failure in obtaining the last known location. 
    .addOnFailureListener {
        // TODO: Define callback for API call failure.
    }

The getLastLocation() method obtains the device location from the system cache. If the obtained device location is null, the possible cause is that the system cache has been cleared. In this case, you need to call the requestLocationUpdates() method to obtain the device location and update the cache, and then call the getLastLocation() method to obtain the device location.

Using the Mock Location Function

To use the mock location function, go to Settings > System & updates > Developer options > Select mock location app and select the desired app. (If Developer options is unavailable, go to Settings > About phone and tap Build number for seven consecutive times. Then, Developer options will be displayed on System & updates.)

  1. Apply for the mock location permission in the AndroidManifest.xml file.
    <uses-permission
        android:name="android.permission.ACCESS_MOCK_LOCATION"
        tools:ignore="MockLocation,ProtectedPermissions" />
  2. Call setMockMode(boolean isMockMode) to set the mock mode.
    Java
    // Set the mock mode. Pass true to enable it; pass false to disable it.
    boolean mockFlag = true;
    fusedLocationProviderClient.setMockMode(mockFlag).addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            Log.i(TAG, "setMockMode onSuccess");
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(Exception e) {
            Log.i(TAG, "setMockMode onFailure:" + e.getMessage());
        }
    });
    Kotlin
    // Set the mock mode. Pass true to enable it; pass false to disable it.
    val mockFlag = true
    fusedLocationProviderClient.setMockMode(mockFlag)
        .addOnSuccessListener { Log.i(TAG, "setMockMode onSuccess") }
        .addOnFailureListener { e ->
            Log.i(TAG,"setMockMode onFailure:" + e.message)
        }
  3. Call setMockLocation(Location mockLocation) to set a mock location.
    Java
    // Set a mock location.
    final Location mockLocation = new Location(LocationManager.GPS_PROVIDER);
    mockLocation.setLongitude(118.76);
    mockLocation.setLatitude(31.98);
    fusedLocationProviderClient.setMockLocation(mockLocation)
        // Define callback for success in setting the mock location information.
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.i(TAG, "setMockLocation onSuccess");
            }
        })
        // Define callback for failure in setting the mock location information.
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                Log.i(TAG, "setMockLocation onFailure:" + e.getMessage());
            }
        });
    Kotlin
    // Set a mock location.
    val mockLocation = Location(LocationManager.GPS_PROVIDER)
    mockLocation.longitude = 118.76
    mockLocation.latitude = 31.98
    fusedLocationProviderClient.setMockLocation(mockLocation) 
        // Define callback for success in setting the mock location information.
        .addOnSuccessListener {
            Log.i(
                TAG,
                "setMockLocation onSuccess"
            )
        } 
        // Define callback for failure in setting the mock location information.
        .addOnFailureListener { e ->
            Log.i(
                TAG,
                "setMockLocation onFailure:" + e.message
            )
        }