#Android

Integrate our SDK in your Android app.

#Quick Start

GeoSpark provides an Android SDK that enables App developers to track location, geofence and trips.


#Step 1: Install SDK

Install the SDK to your project via Gradle in Android Studio and add the dependencies below in your app build.gradle file.


android { 
  ..... 
  compileOptions { 
        sourceCompatibility JavaVersion.VERSION_1_8 
        targetCompatibility JavaVersion.VERSION_1_8 
  } 
  ...... 
} 
dependencies { 
        implementation 'com.geospark.android:geospark:2.1.1' 
}

#Step 2: Initialize SDK

Initialize the SDK in your PublishKey.


//In onCreate method of your Application class 
//include the code below.

public void onCreate() {
    super.onCreate();
    GeoSpark.initialize(this, "PUBLISH_KEY");
    ...
}    

#Step 3: Create User

GeoSpark SDK needs a User ID object to identify the device.


GeoSpark.createUser(this,"User Description", new GeoSparkCallBack() {
    @Override
    public void onSuccess(GeoSparkUser geoSparkUser) {
                geoSparkUser.getUserId();
    }
    @Override
    public void onFailure(GeoSparkError geoSparkError) {
                geoSparkError.getErrorCode();
                geoSparkError.getErrorMessage();
    }
});

#Step 4: Start Location Tracking

To start tracking the location.


//To enable location, call the requestLocationPermissions  
//and requestLocationServices method.

if(!GeoSpark.checkLocationPermission(this)) {
    GeoSpark.requestLocationPermission(this);
} else if (!GeoSpark.checkLocationServices(this)) {
    GeoSpark.requestLocationServices(this);
} else{
    //Call this method to start tracking the location.  
    GeoSpark.startTracking(this);
}      

#Utility Methods

#Initialize SDK

Initialize the SDK in your PublishKey


GeoSpark.initialize(this, "PUBLISH_KEY");

#Set DeviceToken

GeoSpark SDK is capable of sending push notifications to your users. Add Firebase to your Android project to get device token.


GeoSpark.setDeviceToken(this, "FCM DeviceToken");

#Get DeviceToken

To get FCM DeviceToken from SDK.


GeoSpark.getDeviceToken(this);

#Create User

GeoSpark SDK needs an User ID object to identify the device. The SDK has a convenience method createUser() to create a user which returns User ID.


GeoSpark.createUser(this,"User Description", new GeoSparkCallBack() {
  @Override
  public void onSuccess(GeoSparkUser geoSparkUser) {
              geoSparkUser.getUserId();
  }
  @Override
  public void onFailure(GeoSparkError geoSparkError) {
              geoSparkError.getErrorCode();
              geoSparkError.getErrorMessage();
  }
});

#Get User

If you already have an User ID, then SDK has a convenience method getUser() to start the session for the existing user.


GeoSpark.getUser(this, "userId", new GeoSparkCallBack() {
  @Override
  public void onSuccess(GeoSparkUser geoSparkUser) {
              geoSparkUser.getUserId();
  }
  @Override
  public void onFailure(GeoSparkError geoSparkError) {
              geoSparkError.getErrorCode();
              geoSparkError.getErrorMessage();
  }
});    

#User Description

Adding description for the user makes it easier for you to identify your users, while tracking them in SDK. GeoSpark SDKs provide you with the option to modify the description any time for a user. This can also help you in easily identifying users on dashboard simply via the description.


GeoSpark.setDescription(this, "User Description", new GeoSparkCallBack() {
  @Override
  public void onSuccess(GeoSparkUser geoSparkUser) {
        geoSparkUser.getUserId();
  }
  @Override
  public void onFailure(GeoSparkError geoSparkError) {
      geoSparkError.getErrorCode();
      geoSparkError.getErrorMessage();
  }
});    

#Toggle User Events

Use this method after user creation to enable user events for geofence, activity and trips. By default, all user events will be disabled post user creation.


GeoSpark.toggleEvents(this, geofence, trip, activity, new
GeoSparkEventsCallback() {
      @Override
      public void onSuccess(GeoSparkEvents geoSparkEvents) {
            geoSparkEvents.isActivityEventsActive();
            geoSparkEvents.isGeofenceEventsActive();
            geoSparkEvents.isTripEventsActive();
      }
      @Override
      public void onFailure(GeoSparkError geoSparkError) {
            geoSparkError.getErrorCode();
            geoSparkError.getErrorMessage();
      }
});

#Get User Event Status

Use this method after user creation to get the current status of user events for geofence, activity and trips


GeoSpark.getEventsStatus(this, new GeoSparkEventsCallback() {
  @Override
  public void onSuccess(GeoSparkEvents geoSparkEvents) {
      geoSparkEvents.isActivityEventsActive();
      geoSparkEvents.isGeofenceEventsActive();
      geoSparkEvents.isTripEventsActive();
  }
  @Override
  public void onFailure(GeoSparkError geoSparkError) {
      geoSparkError.getErrorCode();
      geoSparkError.getErrorMessage();
  }
});

#Check Location Permission

Check whether your App has location permission. Returns a boolean, which is true if the location permission has been granted, and false otherwise.


GeoSpark.checkLocationPermission(this);

#Check Location Services

Check whether the device has location services enabled. Returns a boolean, which is true if the location location services is ON, and false otherwise.


GeoSpark.checkLocationServices(this);

#Request Location Permission

Call this method to request user to enable location permissions.


GeoSpark.requestLocationPermission(this);

//Callback from request location permission method.

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
   switch (requestCode) {
      case GeoSpark.REQUEST_CODE_LOCATION_PERMISSION:
        if (grantResults.length > 0
          && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
          if (ContextCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
            }
        }
      break;
   }
}

#Request Location Services

Call this method to enable location services.


GeoSpark.requestLocationServices(this);

//Callback from request location services method.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   if (requestCode == GeoSpark.REQUEST_CODE_LOCATION_ENABLED) {
   }
}

#Start Location Tracking

To start tracking the user location.


GeoSpark.startTracking(this);

#Check Location Tracking

Check whether location tracking is started or not. This method returns boolean value.


GeoSpark.isLocationTracking(this);

#Stop Location Tracking

You can stop tracking the user location.


GeoSpark.stopTracking(this);

#Location listener

To listen for location in the background, create a class that implements GeoSparkReceiver. Then, register the receiver by adding a receiver element to the application element in your manifest.


public class MyGeoSparkReceiver extends GeoSparkReceiver {
  @Override
  public void onLocationUpdated(Context context, Location location,
              GeoSparkUser geoSparkUser, String activity){
        // do something with context, location, userId, activity
  }
  @Override
  public void onError(Context context, GeoSparkError geoSparkError) { 
          geoSparkError.getErrorCode();
          geoSparkError.getErrorMessage();
  }
}

<application>
    ...
 <receiver android:name=".MyGeoSparkReceiver"
                android:enabled="true"
                android:exported="false">
     <intent-filter>
     <action android:name="com.geospark.android.RECEIVED"/>
     </intent-filter>
 </receiver>
     ...
</application>

#Current Location

Get current location of the user. You can set the accuracy from 20 to 100 meters (default is 20).


GeoSpark.getCurrentLocation(this, accuracy, new GeoSparkLocationCallback(){
    @Override
    public void location(double latitude, double longitude, double accuracy) {

    }
    @Override
    public void onFailure(GeoSparkError geoSparkError) {
            geoSparkError.getErrorCode();
            geoSp arkError.getErrorMessage();
    }
});

#Update Current Location

Using updateCurrentLocation method, one can update user current location, you can set the accuracy from 15 to 100 meters (default is 15).

Note: This method should be used only if you need to update the current location of the device with better accuracy. Using this method often might consume battery.


GeoSpark.updateCurrentLocation(this, accuracy);

#Start Trip

Start trips in Geospark SDK, using startTrip() method.


GeoSpark.startTrip(this, "tripId", "Description", new GeoSparkTripCallBack() {
  @Override public void onSuccess(GeoSparkTrip geoSparkTrip) {
      geoSparkTrip.getMsg();
  }
  @Override public void onFailure(GeoSparkError geoSparkError) {
      geoSparkError.getErrorCode();
      geoSparkError.getErrorMessage();
  }
});

#End Trip

End trips in Geospark SDK, using endTrip() method.


GeoSpark.endTrip(this, "tripId", new GeoSparkTripCallBack() {
  @Override
  public void onSuccess(GeoSparkTrip geoSparkTrip) {
              geoSparkTrip.getMsg();
  }
  @Override
  public void onFailure(GeoSparkError geoSparkError) {
              geoSparkError.getErrorCode();
              geoSparkError.getErrorMessage();
  }
});        

#Active Trips

Get active trips in GeoSpark SDK, using activeTrips() method.


GeoSpark.activeTrips(this, new GeoSparkTripsCallBack() {
  @Override
  public void onSuccess(List geoSparkActiveTrips) {
              geoSparkActiveTrips;
  }
  @Override
  public void onFailure(GeoSparkError geoSparkError) {
              geoSparkError.getErrorCode();
              geoSparkError.getErrorMessage();
  }
});      

#setTrackingInAppState

Call this method to configure GeoSpark SDK settings for enabling location tracking during given app states.

Parameter Description
SETTINGS Option 1 : GeoSpark.Type.FOREGROUND (or) GeoSpark.Type.BACKGROUND
Option 2 : GeoSpark.Type.ALWAYS_ON

GeoSpark.setTrackingInAppState(this, new GeoSpark.Type[]{Settings}); 

#setTrackingInMotion

Call this method to configure GeoSpark SDK settings for enabling location tracking during given motion tracking.

Parameter Description
SETTINGS Option 1 - GeoSpark.Type.STOP (or) GeoSpark.Type.WALK (or) GeoSpark.Type.RUNNING (or) GeoSpark.Type.BICYCLE (or) GeoSpark.Type.DRIVE
Option 2 - GeoSpark.Type.ALL

GeoSpark.setTrackingInMotion(this, new GeoSpark.Type[]{Settings});

#Notification Opened Handler

By using this method inside FirebaseMessagingService class, track the campaigns impressions and counts.


@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    ...
    intent.putExtra(GeoSpark.EXTRA, GeoSpark.notificationReceiveHandler(remoteMessage.getData()));
    ...
    notificationManager.notify(NotificationID, builder.build());
}


//MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    GeoSpark.notificationOpenedHandler(this, getIntent());
}

#Logout

Logout from GeoSpark SDK, using logout() method.


GeoSpark.logout(this, new GeoSparkLogoutCallBack() {
  @Override
  public void onSuccess(String message) {
            ...
  }
  @Override
  public void onFailure(GeoSparkError geoSparkError) {
        geoSparkError.getErrorCode();
        geoSparkError.getErrorMessage();
  }
});     

#Disable Battery Optimization (android 6+)

When running the SDK on Android 6 (and higher), it is recommended to ask the user to disable battery optimization for your application. This makes sure that detections continue to work properly when the device is in Doze mode. Moreover, on Android Pie, it prevents Adaptive Battery from bucketing your app based on usage and restricting background processing, all of which that can impact the detection quality of the SDK.

After explaining to the user about the benefits of disabling battery optimization, call the disableBatteryOptimization() method of the GeoSpark class.

This will trigger a system dialog asking the user to allow disabling battery optimization for your app.


GeoSpark.disableBatteryOptimization(this);

#Check Battery Optimization

Check battery optimization


GeoSpark.isBatteryOptimizationEnabled(this);

#Troubleshooting

Analyse & resolve your issues.


#Requirements

  • Android 4.2 (API level 16) and above.
  • Devices that support GPS. Devices with only A-GPS are not supported.

#Install SDK Manual

Download and unzip the GeoSpark SDK.

The package contains an aar file. In Android Studio, add the SDK as a module using File > New Module > Import .JAR/.AAR Package. Once Gradle is finished, click File > Project Structure again. Click on App, then Dependencies tab, then click the plus icon in the bottom left, select Module Dependency, click on GeoSpark, then press Ok and wait for Gradle to sync again and include the dependencies separately and sync your project.


android {
  .....
  compileOptions { 
      sourceCompatibility JavaVersion.VERSION_1_8 
      targetCompatibility JavaVersion.VERSION_1_8 
  }
  ......
}
          
dependencies { 
    implementation 'androidx.work:work-runtime:2.0.1' 
    implementation 'com.google.android.gms:play-services-location:15.0.1' 
    implementation 'com.squareup.retrofit2:retrofit:2.4.0' 
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
    implementation 'ch.acra:acra-http:5.2.0'
}
  

#Set up Firebase

Download and unzip the GeoSpark SDK.

If you haven't already, then add Firebase to your Android project.


public class MyFireBaseMessagingService extends FirebaseMessagingService {
  @Override
  public void onNewToken(String token) {
      super.onNewToken(token);
      if (token != null) {
            GeoSpark.setDeviceToken(this, token);
      }
  }
            
  @Override
  public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        .......
    }
}

<application>
    ...
    <service
            android:name=".MyFireBaseMessagingService"
            android:exported="false">
            <intent-filter>
              <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
    </service>
    ...
  </application>
  

#Customize Notification

Android O is coming up with restrictions on background updates, GeoSpark SDK needs use of Foreground service to send location updates. This will not lead to a persistent Foreground notification in the status bar. You can customize small icon and title in this notification.

Name Type Description
smallIconId Integer Resource id for small icon of notification
title String Title of notification

GeoSpark.setNotificationIconAndText(this, smallIconId, title);
  

#Changelog

Keep yourself updated.


#v2.1.1 - (Sep 05, 2019)

Added

  • New utility method to toggle user events and get user events status.

Modified

  • Minor bug fixes and preformation updates.

#v2.0.0 - (June 28, 2019)

Added

  • New utility method Notification Opened Handler.

Modified

  • Redesigns the SDK under the hood to maximize reliability, efficiency, and making integration simple.

#v1.11 - (May 06, 2019)

Added

  • Update SDK Method for Trips V2.

#v1.9 - (March 29, 2019)

Added

  • New utility method to update user's current location.
  • New utility method to check if location tracking is started.

#v1.8 - (March 22, 2019)

Added

  • Added a new method onError under GeoSparkReceiver which will receive all the error codes with description.

Removed

  • Removed the method isMockEnabledinDevice which was used to check if mock application is enabled in the device. This method is replace with receiver for errors.

#v1.7 - (February 27, 2019)

Added

  • New utility method to disable battery optimization.
  • New utility method to check battery optimization.
  • New utility method to check mock enabled.

#v1.5 - (January 31, 2019)

Added

  • New utility method to get user’s current location.

Modified

  • To customize the service notification.

Fixed

  • Improved location tracking.

#v1.4 - (January 22, 2019)

Modified

  • Improvement in location tracking with better crash log support.

#v1.3 - (December 27, 2018)

Fixed

  • Minor and major bug fixes.

#v1.2 - (November 29, 2018)

Added

  • Added DeleteGeofence method.
  • Added Logout method.
  • Added SetDescription method.

Fixed

  • Minor and major bug fixes.

#v1.1 - (November 21, 2018)

Fixed

  • Major and minor bug fixes.

#v1.0 -(October 31, 2018)

Offline Location Updates Method

  • We reliably track location offline and upload to server whenever connection is established back to internet. This feature helps to provide seamless tracking irrespective of internet connectivity issues.

Trips

  • Manage trips through SDK using 'Start Trip' & 'End Trip'.
  • Also track your trips as well using trip routes.

Geofence

  • Using SDK can create personalized geofence & get those geofence list.