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.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
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)
}
}
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.
Java SettingsClient settingsClient = LocationServices.getSettingsClient(this);
Kotlin var settingsClient = LocationServices.getSettingsClient(this)
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.
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)
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:
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
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
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. |
<service android:name="com.huawei.location.service.BackGroundService" android:foregroundServiceType="location" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
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)
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. } } }
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?.
Java fusedLocationProviderClient.disableBackgroundLocation();
Kotlin fusedLocationProviderClient.disableBackgroundLocation()
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. }
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.
To use the mock location function, go to and select the desired app. (If Developer options is unavailable, go to and tap Build number for seven consecutive times. Then, Developer options will be displayed on System & updates.)
<uses-permission
android:name="android.permission.ACCESS_MOCK_LOCATION"
tools:ignore="MockLocation,ProtectedPermissions" /> 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) }
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 ) }