Using the Geofence Service of HUAWEI Location Kit

Ömer Akkuş
Huawei Developers
Published in
4 min readJun 21, 2020

Geofencing is a very useful technology that has a wide variety of applications. It could be used with social media to provide personalized consumer experience, used in marketing and advertising to offer consumer incentives or target consumers in certain business areas or events. It can also be used in personal location tracking to ensure the safety and wellbeing of people, in setting traffic restrictions to prevent vehicle entry in certain locations, and in monitoring entry and exit of assets from specific location to track turnaround time and identify location performance. These are just some applications of geofencing. Developers could maximize the features and usability of their apps by use of geofencing, leading to new opportunities and gaining a competitive advantage.

What is HUAWEI Location Kit?

HUAWEI Location Kit assists developers in enabling their apps to get quick and accurate user locations and expand global positioning capabilities by using GPS, Wi-Fi, and base station locations. One of the main capabilities of the Location Kit is the Geofence Service. The Geofence Service allows developers to set areas of interests so that their apps could receive notifications when specific actions are made, like exiting, entering, or staying in the set areas of interests.

With the Geofence Service, Location Kit detects the distance between the current location of a user device where an app is installed and the set area of interest and notifies the app when the user device enters or exists the area of interest. The Location Kit could also detect the duration in which the user device stays within the area of interest and notifies the app when the detected duration exceeds a set period.

How to develop the Geofence Service?

The HMS Core (APK) must be downloaded on your device and related SDKs must be integrated into your app project before being able to use the Geofence Service API of the HUAWEI Location Kit. For more information on integrating HMS SDK, go to HUAWEI Location Kit Development Preparation.

Developing the Geofence Service

1. Assign app permissions.

a. Apply for ACCESS_FINE_LOCATION permission in the Manifest file.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

b. For Android Q, apply for ACCESS_BACKGROUND_LOCATION permission in the Manifest file.

<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

2. Create a Geofence service client.

a. Create a GeofenceService instance in the OnCreate() method of Activity.

b. Call the geofence-related APIs using the GeofenceService instance.

private GeofenceService geofenceService;private ArrayList<String> idList;private ArrayList<Geofence> geofenceList;private String TAG;private PendingIntent pendingIntent;protected void onCreate(Bundle savedInstanceState) {geofenceService = LocationServices.getGeofenceService(this);pendingIntent = getPendingIntent();idList = new ArrayList<String>();geofenceList = new ArrayList<Geofence>();TAG = "geoFence";}

3. Create and add a geofence

a. Create a geofence instance.

geofenceList.add(new Geofence.Builder().setUniqueId("mGeofence").setValidContinueTime(10000).setRoundArea(latitude, longitude, radius).setConversions(Geofence.ENTER_GEOFENCE_CONVERSION | Geofence.EXIT_GEOFENCE_CONVERSION).build());idList.add("mGeofence");

b. Create a request to add a geofence.

private GeofenceRequest getAddGeofenceRequest() {GeofenceRequest.Builder builder = new GeofenceRequest.Builder();builder.setInitConversions(GeofenceRequest.ENTER_INIT_CONVERSION);builder.createGeofenceList(geofenceList);return builder.build();}

c. Create a new PendingIntent.

private PendingIntent getPendingIntent() {Intent intent = new Intent(this, GeoFenceBroadcastReceiver.class);intent.setAction(GeoFenceBroadcastReceiver.ACTION_PROCESS_LOCATION);return PendingIntent.getBroadcast(this,0, intent,  PendingIntent.FLAG_UPDATE_CURRENT);}

d. Send the request to add a geofence.

public void requestGeoFenceWithNewIntent() {geofenceService.createGeofenceList(getAddGeofenceRequest(), pendingIntent).addOnCompleteListener(new OnCompleteListener<Void>() {@Overridepublic void onComplete(Task<Void> task) {if (task.isSuccessful()) {Log.i(TAG, "add geofence success!");} else {Log.w(TAG, "add geofence failed : " + task.getException().getMessage());}}});}

Deleting geofences

To delete geofences, you can use an ID list. You can also delete a geofence by geofence ID or through PendingIntent.

Sample code:

public void removeWithID() {geofenceService.deleteGeofenceList(idList)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Overridepublic void onComplete(Task<Void> task) { if (task.isSuccessful()) { Log.i(TAG, "delete geofence with ID success!");} else { Log.w(TAG, "delete geofence with ID failed "); } } });}

Processing geofence trigger event

A user notification is broadcasted through PendingIntent when a geofence trigger event is detected.

Sample code:

public class GeoFenceBroadcastReceiver extends BroadcastReceiver {  public static final String ACTION_PROCESS_LOCATION =   "com.huawei.hmssample.geofence.GeoFenceBroadcastReceiver.ACTION_PROC ESS_LOCATION";@Overridepublic void onReceive(Context context, Intent intent) {    if (intent != null) {   final String action = intent.getAction();   StringBuilder sb = new StringBuilder();   String next = "\n"; if (ACTION_PROCESS_LOCATION.equals(action)) {     GeofenceData geofenceData = GeofenceData.getDataFromIntent(intent);   if (geofenceData != null) {  int errorCode = geofenceData.getErrorCode();  int conversion = geofenceData.getConversion();  List<Geofence> list = geofenceData.getConvertingGeofenceList();  Location mLocation = geofenceData.getConvertingLocation();  boolean status = geofenceData.isSuccess();  sb.append("errorcode: " + errorCode + next);  sb.append("conversion: " + conversion + next); for(int i = 0;i < list.size();i++){  sb.append("geoFence id :" + list.get(i).getUniqueId() + next);}  sb.append("location is :" + mLocation.getLongitude() + " " +        mLocation.getLatitude() + next);  sb.append("is successful :" + status);  Log.i(TAG,sb.toString());  } }}}}

The Benefits

Developers could easily implement the Geofence Service in their apps, enabling them to utilize all the features and advantages that the service can provide.

Learn More

To know more information on how to maximize the features and advantages of HUAWEI Location Kit, go to https://developer.huawei.com/consumer/en/hms/huawei-locationkit.

--

--