Getting Started

Overview

The Apsima Android SDK provides an easy way for Android native apps to integrate with Apsima REST Api.

Back To Top

Pre-requisites

  • Android SDK
  • Eclipse
  • Android 4.3 device
  • Google Play Service library

Back To Top

Download Apsima Android SDK and Demo

Please contact Apsima for download information. You can also send an email to support@apsima.com.

Back To Top

Overview of the SDK

Android SDK

Apsima SDK includes a set of projects:

  • IBeacon Library
  • KSPBaseSDK
  • KSPProfileSDK
  • KSPNotificationSDK
  • KSPLocationSDK

Back To Top

IBeacon Library

Apsima’s IBeacon library provides functionality to detect iBeacon from Android apps.

Back To Top

KSPBaseSDK

KSPBaseSDK provides the basic functionalities for all Apsima SDKs, including API Settings, register devices, etc.

Back To Top

KSPProfileSDK

All Apsima features require the end user logged in and authorized with Apsima Server. KSPProfileSDK provides the functionalities for user account management, e.g. Sign Up, Login, Logout, Edit Profile and Change Password.

Back To Top

KSPNotificationSDK

Through Apsima Dashboard or via REST Api, the app developer can create, send or schedule a notification to end users. This SDK provides the functionality to manage notifications, e.g. Synchronize, Read or Delete notifications, etc.

Please consult the ‘Apsima Dashboard Guide’ for more information on how to schedule notifications.

Back To Top

KSPLocationSDK

Apsima supports Geofence and Proximity awareness. You can create a Geofence or Proximity trigger to send a notification to a user or call a callback URL. Please consult the ‘Apsima Dashboard Guide’ for more information on how to manage and use geofence and proximity beacons.

KSPLocationSDK provides the functionality to handle communications between Android devices and Apsima Platform, e.g. download Geofence and Proximity updates from server, monitor the regions and report the region triggered events. KSPLocationSDK will also pass the failed messages to your app when it happens.

Geofence Awareness

When using Apsima’s geofence feature, most of the logic is implemented in the SDK. It will receive and store the geofences to be monitored, register it with Android’s LocationManager, and receive a region triggered event when device has entered or exited a geofence. SDK will also notify your app about this event.

Proximity Awareness

Apsima’s Proximity feature supports 3 different modes: MonitoringGroup, RangingIndividual, and Mixed Mode.

In MonitoringGroup mode, most of the logic is implemented in the SDK. It will receive and store the Beacon Group(s) to be monitored, register them with IBeacon Library, and receive a region triggered event when device is within proximity of a Beacon Group. SDK will notify your app about this event. Note that a Beacon Group can have multiple beacons, but SDK is monitoring the Group and not individual beacons. Monitoring can be done when app is in foreground or background.

In RangingIndividual mode, SDK will receive and store the Beacon Groups to be monitored. It will range all the beacons that belong to these Beacon Groups. IBeacon Library will only generate region triggered event for beacons that belong to these Beacon Groups. When device detects that it is in proximity of one or more beacons, it will get information about each particular beacon, and report it to your app. RangingIndividual mode is only supported when app is in foreground. When app is in background, it will not trigger the region triggered event.

In Mixed mode, SDK will monitor Beacon Group(s) received from Apsima server. When device enters a Beacon Group’s proximity, SDK will start to range all beacons that belong to this Beacon Group. When device detects the beacons, it will get information about each particular beacon, and report it to your app. When app is in background, it will keep monitoring for Beacon Groups and report triggers to server. Note that in background mode ranging mode is not active.

Back To Top

How it works

Initial Setup

Apsima has several libraries and also requires Google Play Services library project. Download these libraries from the download link that has been provided.

Import Apsima libraries into your workspace by clicking File > Import, select Android > Existing Android Code into Workspace, and browse to the copy of the library project to import it. Also, check the “Copy projects to workspace” to copy this library into workspace.

After importing all libraries, please make sure that the libraries dependency is correctly set.

initial-setup

Figure 1. KSPProfileSDK referenced KSPBaseSDK.

initial-setup2

Figure 2. KSPLocationSDK referenced Google-Play-Services, IBeacon and KSPBaseSDK.

initial-setup3

Figure 3. KSPNotificationSDK referenced KSPBaseSDK

initial-setup4

Figure 4. DemoApp references KSPProfileSDK, KSPLocationSDK, and KSPNotificationSDK

Back To Top

KSPBaseSDK

Apsima Credentials

You can grab the API credentials from Apsima dashboard:

  1. Click on Application tab
  2. Click on API option
  3. Take note of API Key, API Server Secret and API Client Secret.

api-credentials

Setup Google Cloud Messaging

Follow Android’s GCM Getting Started to setup GCM implementation and update the information to Apsima Dashboard.

  1. Click on the Application tab under the top header
  2. Click on the API tab on the left
  3. Input your Project Number and App Key (GCM Sender ID and API Key respectively from Google console)
  4. Input your Android application’s package name.

app-package-name

Initialize KSPManager, KSPBaseUtilities, and WebActionsApi

KSPManager must be declared static in your Application object, and initialized in onCreate(). KSPBaseUtilities must be initialized with a context object, your Android app’s package name, and an intent object to your MainActivity class. This is the activity that shows content when user have successfully logged in.
WebActionsApi must be initialized with KSP_BASE_URL, DOMAIN_KEY, API_KEY, and API_SECRET_KEY.

1
2
3
4
5
6
7
mKSPManager = KSPManager.getInstanceForApplication(context);
try {
	KSPBaseUtilities.init(ApsimaDemoUtilities.PACKAGE_NAME, this, new Intent(context, MainActivity.class));
} catch (Exception e) {
	e.printStackTrace();
}
WebActionsApi.init(context, KSP_BASE_URL, DOMAIN_KEY, API_KEY, API_SECRET_KEY);

KSP_BASE_URL must be https://rest.apsima.com. Other Apsima credentials can be obtained from Apsima Dashboard, as explained in Apsima Credential section.

Register device

Registering a device allows Apsima Server to target an individual device and send remote push notification to the registered device. There are two values required to register a device, GCM RegistrationId and userUid. Two places to register a device:

    1. In Application class
      At this time, it is possible that your device has not received GCM RegistrationId. It is also possible that userUid is not available because user has not logged in. Apsima features require end user to login and be authenticated with Apsima Server. A userUid is unique identifier for logged-in user. Apsima save userUid in KSPBaseSettings.

 

1
KSPBaseUtilities.sendBroadcastUpdateCreateDevice(this, KSPBaseSettings.getUserUid(this), gcmRegistrationId);
    1. In GCMIntentService class
      When device received a new GCM RegistrationId, we need to register this device and pass the new value of GCM RegistrationId.

 

1
2
3
4
5
6
7
public void onReceive(Context context, Intent intent) {
	String regId = intent.getExtras().getString("registration_id");
	if(regId != null && !regId.equals("")) {
		Settings.setGcmRegId(context, regId);
		KSPBaseUtilities.sendBroadcastUpdateCreateDevice(context, KSPBaseSettings.getUserUid(context), regId);
	}
}

Note that the communication between SDK and your app is done via intent. This will be true for most cases.

Handle Push Notification

GCMIntentService will manage the different type of push notifications. For example, when it receives a push notification about new KSPNotification, it will notify KSPNotificationManager to handle it. Please see Apsima DemoApp for sample code.

1
2
3
4
5
6
7
8
9
10
protected void onMessage(Context context, Intent intent) {
	String collapseKey = intent.getStringExtra(“collapse_key”);
	int collapseKeyValue = Integer.parseInt(collapseKey); // simplified version.
	if (collapseKeyValue == KSPBaseUtilities.ActionType.KSP_Notification.mCode) {
		..
		KSPNotificationUtilities.sendBroadcastGetKSPNotification(context, KSPBaseSettings.getUserUid(this), id);
	} else {
		// handle other cases.
	}
}
Add permissions in AndroidManifest

These permissions are needed to be added in AndroidManifest.

1
2
3
4
5
6
7
8
<permission
        android:name="com.apsima.demoapp.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
 
    <uses-permission android:name="com.apsima.demoapp.permission.C2D_MESSAGE" />
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
Declare KSPDeviceManager in AndroidManifest

Add this inside your application tag.

1
2
3
4
5
6
7
8
<receiver
 	android:name="com.apsima.basesdk.services.KSPDeviceManager"
 	android:exported="false" >
 	<intent-filter>
		<action android:name="com.apsima.demoapp.ACTION_UPDATE_CREATE_DEVICE" />
		<action android:name="com.apsima.demoapp.ACTION_REPORT_TIME_IN_APP" />
	</intent-filter>
</receiver>

Back To Top

KSPProfileSDK

Initialize KSPProfileUtilities

KSPProfileUtilities needs to be initialized after KSPBaseUtilities initialization.

1
2
3
4
5
6
try {
	KSPBaseUtilities.init(ApsimaDemoUtilities.PACKAGE_NAME, this);
	KSPProfileUtilities.init();
} catch (Exception e) {
	e.printStackTrace();
}
Declare KSPProfileManager in AndroidManifest

Add this inside application tag.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<receiver
        android:name="com.apsima.profilesdk.services.KSPProfileManager"
        android:exported="false" >
        <intent-filter>
                <action android:name="com.apsima.demoapp.ACTION_GET_PROPERTIES" />
                <action android:name="com.apsima.demoapp.ACTION_GET_USER_PROPERTIES" />
                <action android:name="com.apsima.demoapp.ACTION_GET_ALL_USER_PROPERTIES" />
                <action android:name="com.apsima.demoapp.ACTION_UPDATE_USER_PROPERTIES" />
                <action android:name="com.apsima.demoapp.ACTION_SYNC_USER_PROFILE" />
                <action android:name="com.apsima.demoapp.ACTION_SYNC_USER_PROFILE_CONTINUED" />
                <action android:name="com.apsima.demoapp.ACTION_SYNC_USER_SETTING" />
                <action android:name="com.apsima.demoapp.ACTION_UPDATE_USER_SETTING" />
                <action android:name="com.apsima.demoapp.ACTION_EXTEND_LOGIN" />
        </intent-filter>
</receiver>
Sign up

User can sign up to create a new account by providing full name, username, email and password. Upon successful sign up process, user can use the username and password to login to the app.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
ApiUser user = new ApiUser(uuid, username, password, firstName, lastName, email, KSPBaseUtilities.USER_TYPE);
try {
	KSPProfileWebService.createUser(context, user, new CreateUserListener() {
		@Override
		public void onWebActionSuccess(ApiUser result) { 	// Handle login success, go to login view. 	}
 
		@Override
		public void onWebActionFailed(WebException ex) { // Handle login failed }
 
		@Override
		public void onWebActionComplete() { }
	});
} catch (Exception e) { 
	// Handle exception, listener is not set.
} catch (WebException webEx) {
	// Handle WebException, parameter may be invalid.
}

Errors:

– Full name is required;
– Username is required;
– Email is required;
– Invalid Email;
– Password is required;
– Password must be 6-32 characters;
– Password and Confirm password must match;
– Duplicate username;
– Invalid username or Email;

 

Login

User can login to the app using their username and password. Upon successful login process, SDK will generate an authentication token. When logging in, device can request the authentication duration, default is LongLived. User can login using username, email or both. The default is UsernameOrEmail. Default values will be used when these parameters are null.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
try {
	KSPProfileWebService.loginUser(context, username, password, 
					ApiUsernameValidationType.UsernameOrEmail,
					ApiAuthenticationDurationType.LongLived,
					deviceUid, 
					new LoginUserListener() {
		@Override
		public void onWebActionSuccess(ApiUserAuthentication result) {
			KSPProfileUtilities.startMainActivityWithLoginStatus(context, result); // go to main view.
		}
		@Override
		public void onWebActionFailed(WebException ex) { // Handle login failed. }
 
		@Override
		public void onWebActionComplete() { }
 
	});
} catch (Exception e) {
	// Handle exception, listener is not set.
} catch (WebException webEx) {
	// Handle WebException, parameter may be invalid.

Errors:

– Username is required;
– Password is required;
– Password must be 6-32 characters;
– Invalid username or password;

 

Forgot Password

When user forgets their password, they can request server to reset their password. If user provides a valid username or email, a new temporary password will be sent to the user’s email.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
try {
	KSPProfileWebService.sendPasswordForgetEmail(context, usernameOrEmail, 
			ApiUsernameValidationType.UsernameOrEmail, new GenericProfileListener() {
		@Override
		public void onWebActionSuccess(String result) { // Handle successful request. }
 
		@Override
		public void onWebActionFailed(WebException ex) { // Handle failed request. }
 
		@Override
		public void onWebActionComplete() { }
	});
} catch (Exception e) {
	// listener is not set.
} catch (WebException webEx) {
	// Handle WebException, parameter may be invalid.
}

Errors:

– Username or Email is required;

 

Get Profile

User can get their profile data. This method can only be called after user is logged in, otherwise you will get a nil object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
try {
	KSPProfileWebService.getProfile(context, userUid, new GetProfileListener() {
 
@Override
		public void onWebActionSuccess(ApiUser result) { //Handle succesful request, save user profile. }
 
		@Override
		public void onWebActionFailed(WebException ex) { //Handle failed request. }
 
		@Override
		public void onWebActionComplete() { }
	});
} catch (Exception e) {
 
} catch (WebException webEx) {
	// Handle WebException, parameter may be invalid.	
}

Error:

– UserUid is required;
– User is unauthorized;

 

Update Profile

User can update their username, full name or email address. This method can only be called after user is logged in.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
try {
	KSPProfileWebService.updateUser(context, user, new GetUserListener() {
 
		@Override
		public void onWebActionSuccess(ApiUser result) { //Handle successful request. }
 
		@Override
		public void onWebActionFailed(WebException ex) { //Handle failed request.}
 
		@Override
		public void onWebActionComplete() { }
 
	});
} catch (Exception e) {
 
} catch (WebException webEx) {
 
}

Error:

– Full name is required;
– Username is required;
– Email is required;
– Invalid Email;
– User is unauthorized;

 

Update Profile Image

User can change their profile image, either by taking a new picture or using an existing one. This method can only be called after user is logged in. Please see Apsima DemoApp for sample code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
try {
	String userUid = KSPBaseSettings.getUserUid(context);
	KSPProfileWebService.updateUserProfileImage(context, userUid, picBitmap, new UpdateUserProfileImageListener() {
 
		@Override
		public void onWebActionSuccess(String result) { //Handle successful request. }
 
		@Override
		public void onWebActionFailed(WebException ex) { //Handle failed request. }
 
		@Override
		public void onWebActionComplete() { }
	});
} catch (Exception e) {
 
} catch (WebException webEx) {
	//Handle WebException, parameter may be invalid.
}
Change Password

User can change their password by providing their old password and new password. This method can only be called after user is logged in.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
try {
	KSPProfileWebService.changeUserPassword(context, userUid, newpass, oldpass,
			 ApiAuthenticationDurationType.LongLived, new ChangePasswordListener() {
 
		@Override
		public void onWebActionSuccess(ApiUserAuthentication result) { //Handle successful request.}
 
		@Override
		public void onWebActionFailed(WebException ex) { // Handle failed request.}
 
		@Override
		public void onWebActionComplete() { }
	});
} catch (Exception e) {
 
} catch (WebException webEx) {
 
}

Errors:

– Password is required;
– Password must be 6-32 characters;
– User in unauthorized;

 

Reset Password

User must reset their password when logged in using a temporary password. This method can only be called after user is logged in.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
try {
	KSPProfileWebService.resetPassword(context, uid, newpass, 
			ApiAuthenticationDurationType.LongLived,  new ResetPasswordListener() {
 
		@Override
		public void onWebActionSuccess(ApiUserAuthentication result) { //Handle successful request. }
 
		@Override
		public void onWebActionFailed(WebException ex) { //Handle failed request.}
 
		@Override
		public void onWebActionComplete() { }
	});
} catch (Exception e) {
 
} catch (WebException webEx) {
 
}

Errors:

– Password is required;
– Password must be 6-32 characters;
– User in unauthorized;

 

Implement BroadcastReceiver in your application

KSPProfileSDK may broadcast intents to notify client app about these issues:

– User profile or user profile image has been updated.
– Forced logout. User’s authentication credential has expired, thus they will need to login again to get new authentication token. Please see Apsima DemoApp for sample code.

Back To Top

KSPNotificationSDK

Initialize KSPNotificationUtilities

KSPNotificationUtilities needs to be initialized after KSPBaseUtilities initialization.

1
2
3
4
5
6
try {
	KSPBaseUtilities.init(ApsimaDemoUtilities.PACKAGE_NAME, this);
	KSPNotificationUtilities.init();
} catch (Exception e) {
	e.printStackTrace();
}
Declare KSPNotificationManager, KSPNotificationPurgeManager in AndroidManifest

Add these receivers inside application tag. KSPNotificationManager will handle communication with server to get updates and setting up time to delete all expired KSPNotifications. KSPNotificationPurgeManager will handle deleting expired KSPNotifications.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<receiver
   	android:name="com.apsima.kspnotificationsdk.services.KSPNotificationManager" 
   	android:exported="false" >
	<intent-filter>
		<action android:name="com.apsima.demoapp.ACTION_SYNC_KSP_NOTIFICATION" />
		<action android:name="com.apsima.demoapp.ACTION_SYNC_KSP_NOTIFICATION_CONTINUED" />
		<action android:name="com.apsima.demoapp.GET_KSP_NOTIFICATION" />
		<action android:name="com.apsima.demoapp.ACTION_SET_PURGE_ALARM" />
		<action android:name=
			"com.apsima.demoapp.NOTIFY_USER_SETTING_KSP_NOTIFICATION_PUSH_ENABLE_CHANGED" />
		<action android:name=
		"com.apsima.demoapp.NOTIFY_USER_SETTING_KSP_NOTIFICATION_PUSH_ENABLE_UPDATE_FAILED" />
	</intent-filter>
</receiver>
<receiver android:name="com.apsima.kspnotificationsdk.services.KSPNotificationPurgeManager" 
	 android:exported="false"/>
Get Notification Updates

Call KSPNotificationUtilities.sendBroadcastSyncKSPNotificationIntent(context, userUid) to let KSPNotificationManager to get all potential updates of notifications. When it finishes getting the updates, KSPNotificationManager will send intent to notify client app about the updates.

1
2
3
4
5
6
7
8
9
private class OffersReceiver extends BroadcastReceiver {
 
	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equalsIgnoreCase(KSPNotificationUtilities.NOTIFY_KSP_NOTIFICATIONS_UPDATED)) {
			// Update your UI
		}
	}
}
Delete a KSPNotification

This will notify server when user deletes a KSPNotification. Server will mark it as deleted and notify user’s other devices (if any) to synchronize them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
try {
   	KSPNotificationWebService.deleteKSPNotification(context, userUid, notificationUid, 
			new DeleteKSPNotificationUpdateListener() {
		@Override
		public void onWebActionSuccess(String result) { //Handle successful request, update database and UI. }
 
		@Override
		public void onWebActionFailed(WebException ex) { //Handle failed request. }
 
		@Override
		public void onWebActionComplete() { }
   	});
} catch (Exception e) {
 
} catch (WebException e) {
 
}
Get KSPNotification content

This will get the content of KSPNotification in html format that can be shown using a WebView.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
try {
	KSPNotificationWebService.getKSPNotificationContent(context, userUid, notificationUid, 
	new GetKSPNotificationContentListener() {
 
		@Override
		public void onWebActionSuccess(String result) { 
			loadData(result, "text/html", null); // Show result in a WebView.
		}
 
		@Override
		public void onWebActionFailed(WebException ex) { // Handle failed request. }
 
		@Override
		public void onWebActionComplete() { }
	});
} catch (Exception e) {
 
} catch (WebException e) {
 
}
Read a KSPNotification

This will notify server when user opens a KSPNotification. It also passes true if it is opened from System Notification, and false if opened from elsewhere. Note that you should call this only if notification has never been read before; otherwise it will overwrite data on server.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
if (!notification.getIsRead()) {
	try {
		KSPNotificationWebService.readKSPNotification(context, userUid, notificationUid, isReadFromNotification, 
				new ReadKSPNotificationUpdateListener () {	
			@Override
			public void onWebActionSuccess(String result) { //Handle successful request, update read flag. }
 
			@Override
			public void onWebActionFailed(WebException ex) { //Handle failed request. }
 
			@Override
			public void onWebActionComplete() { }
		});
	} catch (Exception e) {
 
	} catch (WebException webEx) {
 
	}
}
Implement BroadcastReceiver in your application

KSPNotificationSDK may broadcast intents about these issues:

– An individual KSPNotification has just been received. This intent will get sent when user clicks on the Android’s notification. KSPNotification’s uid can be retrieved from intent’s extra.
– When 4 or more KSPNotifications have been received, Android’s notification will be consolidated. This intent will get sent when user click on consolidated Android’s notification.

Back To Top

KSPLocationSDK

This library requires Google Play Service Library for geofencing and IBeacon Library for proximity awareness. You can download both libraries from links provided by Apsima. For more information about Google Play Service Library, you can read “Set Up Google Play Services SDK” documentation from Android Developer website (http://developer.android.com/google/play-services/setup.html). It will also require that Google Play Services is installed on the device.

Initialize KSPLocationUtilities

KSPLocationUtilities need to be initialized after KSPBaseUtilities initialization. If the app uses iBeacon features, you need to pass what scanning mode to be used by KSPMicroLocationService. Otherwise pass null object.

1
2
3
4
5
6
try {
	KSPBaseUtilities.init(ApsimaDemoUtilities.PACKAGE_NAME, this);
	KSPLocationUtilities.init(KSPBeaconGroupScanModeMix);
} catch (Exception e) {
	e.printStackTrace();
}

Geofence

When using Apsima’s geofence feature, KSPLocationSDK will handle most of the logic. It will receive the geofences to be monitored, register these geofences with Android’s LocationManager, and receive the event when it is triggered.

Add permissions in AndroidManifest

Access Fine Location will enable app to access precise location from location sources such as GPS, cell towers and Wi-Fi.
Receive Boot Completed will enable app to start monitoring geofences right after device completed its boot sequence.

1
2
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Declare KSPGeofenceManager, KSPGeofenceIntentService in AndroidManifest

KSPGeofenceManager will handle communication with server to get updates. It will also get notified when device has just finished its boot sequence, where it will send broadcast to start monitoring geofences. KSPGeofenceIntentService will handle registering and removing geofences to be monitored. RegionTransitionsReceiverIntentService will handle actions when geofences event triggered.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<receiver android:name="com.apsima.locationsdk.services.KSPGeofenceManager"
	android:exported="false" >
	<intent-filter>
		<action android:name="com.apsima.demoapp.ACTION_SYNC_GEOFENCES" />
		<action android:name="android.intent.action.BOOT_COMPLETED" />
	</intent-filter>
</receiver>
<service android:name="com.apsima.locationsdk.services.KSPGeofenceIntentService"
	android:label="@string/app_name"
	android:exported="false">
	<intent-filter>
		<action android:name="com.apsima.demoapp.ACTION_REGISTER_GEOFENCES" />
		<action android:name="com.apsima.demoapp.ACTION_UNREGISTER_GEOFENCES" />
		<action android:name="com.apsima.demoapp.ACTION_UNREGISTER_ALL_GEOFENCES" />
		<action android:name="com.apsima.demoapp.ACTION_GEOFENCE_DISABLED" />
	</intent-filter>
</service>
<service android:name="com.apsima.locationsdk.location.RegionTransitionsReceiverIntentService"
	android:label="@string/app_name"
	android:exported="false">
</service>
Implement BroadcastReceiver in your application

KSPLocationSDK may broadcast intent regarding these issues:

– Google Play Service is not available. User should be prompted to install Google Play Service package from Google Play Store (https://play.google.com/store/apps/details?id=com.google.android.gms)
– Geofence event has been triggered. Please see Apsima DemoApp for sample code.

 

Proximity

Add permissions in AndroidManifest

When using iBeacon feature, KSPLocationSDK needs the device’s Bluetooth enabled. It also needs Bluetooth Low Energy capability. By setting android:required=”false”, app can be installed on devices that do not have Bluetooth LE capability. This means that iBeacon feature will not work on such devices. RECEIVE_BOOT_COMPLETED will enable app to start monitoring for iBeacon right after device completed its boot sequence.

1
2
3
4
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>    
<uses-feature android:name="android.hardware.bluetooth_le" android:required="false"/>
Declare KSPMicroLocationManager, KSPMicroLocationService in AndroidManifest

KSPMicroLocationManager will handle communication with server to get updates. It will also get notified when device has just finished its boot sequence, where it will send broadcast to start monitoring BeaconGroup. KSPMicroLocationService will handle most logic of IBeacon implementation. We also need to declare IBeaconService and IBeaconIntentProcessor from Apsima IBeaconLibrary.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<service android:name="com.apsima.locationsdk.services.KSPMicroLocationService"
	android:label="KSPMicroLocationService"
	android:exported="false">
</service>
<receiver android:name="com.apsima.locationsdk.services.KSPMicroLocationManager"
	android:exported="false" >
	<intent-filter>
		<action android:name="com.apsima.demoapp.ACTION_SYNC_IBEACON_GROUP" />
		<action android:name="com.apsima.demoapp.ACTION_SYNC_KSP_NOTIFICATION_BEACON_GROUP" />
		<action android:name="com.apsima.demoapp.ACTION_UPDATE_IBEACON_BACKGROUND_MODE" />
		<action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
		<action android:name="android.intent.action.BOOT_COMPLETED" />
	</intent-filter>
</receiver>
<!-- Objects below are from Apsima IBeaconLibrary -->
<service android:name="com.apsima.ibeacon.service.IBeaconService"
	android:enabled="true"
	android:exported="false"
	android:label="iBeacon">
</service>    
<service android:name="com.apsima.ibeacon.IBeaconIntentProcessor"
	android:enabled="true" >
</service>
Implement BroadcastReceiver in your application

KSPLocationSDK may broadcast intent regarding these issues:

– Bluetooth is disabled: IBeacon feature is using Bluetooth connection, thus you may want to ask user to turn on device’s Bluetooth.
– IBeaconGroup has been triggered: Please see Apsima DemoApp for sample code.
– Beacon ranged event: SDK will notify client app that one or more Beacon has been detected. Please see Apsima DemoApp for sample code.

Back To Top

Appendices

Appendix A. Intents from SDK to Client App

Intent’s actions and their extras are initialized with Client app’s package name as its prefix. For example, KSPNotificationUtilities.ACTION_SHOW_ALL_KSP_NOTIFICATION is represented by this String: “com.apsima.demoapp.ACTION_SHOW_ALL_KSP_NOTIFICATION”, where com.apsima.demoapp is the package name of Apsima DemoApp.

KSPProfileUtilities.ACTION_LOGIN_RESULT_FROM_SDK

Extra: KSPProfileUtilities.EXTRA_API_USER_AUTHENTICATION. This is a Json string of ApiUserAuthentication object.

Purpose: Notify client app that user has just logged in. The extra holds authentication data. If duration type is ApiAuthenticationDurationType.Temporary, it means that user logged in using a temporary password. The authentication token will only be valid for a short time.

What to do: Prompt user to reset their password.

KSPBaseUtilities.ACTION_FORCE_LOGOUT_USER

Extra: KSPBaseUtilities.EXTRA_IS_FORCED_LOGOUT. This is true when user authentication has failed because of token is invalid or expired. It is false when user is logging out intentionally.

Purpose: Notify client app that user authentication data has been expired, invalidated or missing.

What to do: Clear all data for this current user. This will include ClientApp’s data and also data from each of Apsima SDK, which can be cleared by calling their Utilities class clearGeneralData() function. Then prompt user to re-login.

KSPProfileUtilities.ACTION_USER_PROFILE_UPDATED

Extra: None.

Purpose: Notify client app that user profile data has been updated. This happens when user has just logged in or the data has been changed from other device.

What to do: Normally we will need to refresh our UI to show these changes, if this user profile view is currently shown.

KSPProfileUtilities.ACTION_USER_PROFILE_IMAGE_UPDATED

Extra: None.

Purpose: Notify client app that user profile image has been updated. This happens when user has just logged in or the profile image has been changed from other devices.

What to do: Normally we will need to refresh our UI to show these changes, if this user profile view is currently shown.

KSPNotificationUtilities.ACTION_SHOW_ALL_KSP_NOTIFICATION

Extra: None.

Purpose: Notify client app that User has clicked on a consolidated Android notification. This happens when 4 or more KSPNotifications are received and have not been viewed.

What to do: Normally we should show all KSPNotifications stored locally on the device.

KSPNotificationUtilities.ACTION_SHOW_KSP_NOTIFICATION

Extra: KSPNotificationUtilities.EXTRA_KSP_NOTIFICATION_UID. This is uid of this specific KSPNotification.

Purpose: Notify client app that user has clicked on an individual Android notification.

What to do: Normally we should show the content of this KSPNotification. Client app can get the content using the uid in extra.

KSPLocationUtilities.NOTIFY_GEOFENCE_TRIGGERED

Extras: KSPLocationUtilities.EXTRA_GEOFENCE_UID. This is Uid of the geofence. KSPLocationUtilities.EXTRA_TRIGGER_DIRECTION. This is direction of the trigger event: enter (1), exit (2).

Purpose: Notify client app that a geofence event has just been triggered.

What to do: Get more information about this geofence using its Uid or start Client app’s specific tasks.

KSPLocationUtilities.NOTIFY_IBEACON_GROUP_TRIGGERED

Extras: KSPLocationUtilities.EXTRA_IBEACON_GROUP_UID. This is the Uid of the Beacon Group. KSPLocationUtilities.EXTRA_IBEACON_GROUP_NAME. This is name of the Beacon Group. KSPLocationUtilities.EXTRA_TRIGGER_DIRECTION. This is direction of the trigger event defined by KSPLocationUtilities.TriggerDirection: entered (1), exited (2).

Purpose: Notify client app that a Beacon Group event has just been triggered.

What to do: Get more information about this Beacon Group using its Uid or start Client app’s specific tasks.

KSPLocationUtilities.NOTIFY_KSP_BEACON_RANGED_LIST_AVAILABLE

Extra: KSPLocationUtilities.EXTRA_BEACON_RANGE_LIST_NAME. This is the name associated with list of beacons stored in KSPManager.

Purpose: Notify client app that a list of beacon has been detected.

What to do: KSPManager holds the Json string of the List. Get it by calling KSPManager.getInstanceForApplication().getKSPBeaconRanged(listName).

KSPLocationUtilities.NOTIFY_BLUETOOTH_IS_DISABLED

Extra: None.

Purpose: SDK has determined that device’s Bluetooth is currently disabled. IBeacon feature requires Bluetooth to be enabled.

What to do: User may be prompted to turn on the Bluetooth.

KSPLocationUtilities.ACTION_GOOGLE_PLAY_SERVICE_UNAVAILABLE

Extra: KSPLocationUtilities.EXTRA_GOOGLE_PLAY_SERVICE_ERROR_CODE. This error code is given by GooglePlayServiceUtils. This error may occur because either Google Play Service is not installed or requires a newer version.

Purpose: Notify client app that Google Play Service is unavailable.

What to do: Prompt user to install Google Play Service from Google Play Store.

KSPNotificationUtilities.NOTIFY_USER_SETTING_KSP_NOTIFICATION_PUSH_ENABLE_UPDATED

Extra: None.

Purpose: Notify client app that User Setting for KSP Notification Push Enable has been updated.

What to do: Get the value from KSPNotificationSettings.getKSPNotificationPushFeatureEnabled(), and set the Switch/UI accordingly.

KSPNotificationUtilities.NOTIFY_UI_USER_SETTING_UPDATE_FAILED

Extra: KSPBaseUtilities.EXTRA_USER_SETTING_TYPE. This extra defines the type of User Setting that the SDK failed to update with the Apsima server. Currently only UserSettingType.KspNotificationPushEnabled is supported.

Purpose: Notify client app that it failed to update Apsima server about changing this user setting value.

What to do: Notify user.

KSPNotificationUtilities.ACTION_UPDATE_UNREAD_KSP_NOTIFICATION_COUNTER

Extra: KSPNotificationUtilities.EXTRAS_UNREAD_COUNT. Number of unread count.

Purpose: Notify client app that the KSPNotificationDatabase has been updated, thus unread count is modified.

What to do: Get unread count and show it in UnreadCounter object.

 

KSPNotificationUtilities.NOTIFY_KSP_NOTIFICATIONS_UPDATED

Extra: None.

Purpose: Notify client app that KSPNotificationDatabase has been updated.

What to do: Refresh ListView where KSPNotifications are displayed.

Back To Top

Appendix B. Intents from Client App to SDK

Below is a list of intents that can be sent to Apsima SDKs.

KSPBaseUtilities.sendBroadcastUpdateCreateDevice(context, userUid, gcmRegistrationId)

Purpose: KSPDeviceManager should register this device along with userUid and Gcm registration Id to Apsima server. This will allow Apsima server to target an individual device and send remote push notification to the registered device.

Action: KSPBaseUtilities.ACTION_UPDATE_CREATE_DEVICE

Extras: KSPBaseUtilities.EXTRA_GCM_SENDER. This is the gcm registration id. KSPBaseUtilities.EXTRA_USER_UID. This is the current user uid.

KSPProfileUtilities.sendBroadcastSyncUserSetting(context, userUid)

Purpose: KSPProfileManager should request updates to Apsima server regarding User Settings and save it to KSPProfileDatabase.

Action: KSPProfileUtilities.ACTION_SYNC_USER_SETTING

Extras: KSPBaseUtilities.EXTRA_USER_UID. This is the uid of the current user.

KSPProfileUtilities.sendBroadcastGetProperties(context, userUid)

Purpose: KSPProfileManager should request all user properties that Apsima server provides and save them to KSPProfileDatabase.

Action: KSPProfileUtilities.ACTION_GET_PROPERTIES

Extras: KSPBaseUtilities.EXTRA_USER_UID. This is the uid of the current user.

KSPProfileUtilities.sendBroadcastSyncUserProfile(context, userUid)

Purpose: KSPProfileManager should request updates to Apsima server regarding user profile and save them to the local database.

Action: KSPProfileUtilities.ACTION_SYNC_USER_PROFILE

Extras: KSPBaseUtilities.EXTRA_USER_UID. This is the uid of the current user.

KSPLocationUtilities.sendBroadcastSyncGeofencesIntent(context, userUid)

Purpose: KSPGeofenceManager should request updates to Apsima server regarding geofences to be monitored and save them to KSPLocationDatabase. Then, KSPGeofenceManager will send broadcast to run KSPGeofenceIntentService.

Action: KSPLocationUtilities.ACTION_SYNC_GEOFENCES

Extras: KSPBaseUtilities.EXTRA_USER_UID. This is the uid of the current user.

KSPLocationUtilities.sendBroadcastSyncBeaconGroupIntent(context, null)

Purpose: KSPMicroLocationManager should request updates to Apsima server regarding Beacon Groups to be monitored, and save them to KSPLocationDatabase. Then, KSPMicroLocationManager will send a broadcast to run KSPMicroLocationService.

Action: KSPLocationUtilities.ACTION_SYNC_IBEACON_GROUP

Extras: KSPBaseUtilities.EXTRA_OWNER_UID. Pass null, currently not implemented.

KSPLocationUtilities.startServiceMonitorOrRangingBeacon(context, userUid, backgroundMode)

Purpose: Start KSPMicroLocationService in Scanning Mode as it is initialized in KSPLocationUtilities. KSPMicroLocationService will get the BeaconGroups to be monitored from KSPLocationDatabase.

Action: KSPLocationUtilities.ACTION_START_MONITORING_OR_RANGING_WITH_BACKGROUND_MODE

Extras: KSPLocationUtilities.EXTRA_IBEACON_BACKGROUND_MODE. IBeaconService can run in background mode (true) or foreground mode (false). Client app must change this value using KSPLocationSettings.setBeaconManagerBackgroundMode(isBackgroundMode). KSPBaseUtilities.EXTRA_USER_UID. This is the uid of the current user.

KSPLocationUtilities.sendBroadcastSyncKspNotificationRelatedBeaconGroupIntent( context, userUid, null)

Purpose: KSPMicroLocationManager should request updates about BeaconGroups that are related to any KSPNotification from Apsima server. KSPMicroLocationManager will then query KSPMicroLocationService if device is currently inside the BeaconGroup that has been received.

Action: KSPLocationUtilities.ACTION_SYNC_KSP_NOTIFICATION_BEACON_GROUP

Extras: KSPBaseUtilities.EXTRA_USER_UID. This is the uid of the current user. KSPBaseUtilities.EXTRA_OWNER_UID. Pass null, currently not implemented.

KSPNotificationUtilities.sendBroadcastGetKSPNotification(context, userUid, kspNotificationUid)

Purpose: KSPNotificationManager should get details of the KSPNotification by its Uid from Apsima server. This is called from GCMIntentService.

Action: KSPNotificationUtilities.ACTION_GET_KSP_NOTIFICATION

Extras: KSPNotificationUtilities.EXTRA_KSP_NOTIFICATION_UID. This is the uid of the KSPNotification. KSPBaseUtilities.EXTRA_USER_UID. This is the uid of the current user.

KSPNotificationUtilities.sendBroadcastSyncKSPNotificationIntent(context, userUid)

Purpose: KSPNotificationManager should request updates to the Apsima server regarding KSPNotification, store the list of KSPNotifications into KSPNotificationDatabase, and send broadcast to notify client app about the update.

Action: KSPNotificationUtilities.ACTION_SYNC_KSP_NOTIFICATION

Extras: KSPBaseUtilities.EXTRA_USER_UID. This is the current user uid.

KSPNotificationUtilities.sendBroadcastPurgeExpiredKSPNotification(context)

Purpose: KSPNotificationPurgeManager should find expired KSPNotifications in the local database and delete them. This intent will also be called from KSPNotificationManager.

Action: None.

Extras: None.

Back To Top

Appendix C. Miscellaneous

KSPBaseSettings.setUserUid(userUid) and KSPBaseSettings.getUserUid(context)

Purpose: When user logs in, the SDK stores the currently logged in user Uid. When user logs out, we should clear this value by calling KSPBaseUtilities.clearGeneralData().

Where: This value is set by the KSPProfileSDK upon successful login.

KSPBaseSettings.setAuthenticationId(authId) and KSPBaseSettings.getAuthenticationId(context)

Purpose: When user logs in, SDK stores the current authentication uid. When user logs out, we should clear this value by calling KSPBaseUtilities.clearGeneralData().

Where: This value is set by the KSPProfileSDK upon successful login.

KSPBaseUtilities.initializeDeviceWidth(context)

Purpose: This will allow KSPNotification items to be drawn with the correct ratio of height/width.

Where: MainActivity.onCreate().

KSPBaseSettings.setAppInForeground(context, boolean)

Purpose: This will allow the Apsima SDK to report app usage time. When app is starting in foreground, SDK will record the time. When app goes to background, SDK will calculate how many seconds that app was open and report it to the Apsima server.

Where: In MainActivity.onPause(), call it and pass false because activity is going to background. In MainActivity.onResume(), call it and pass true because activity is going to foreground.

KSPLocationSettings.setBeaconManagerBackgroundMode(context, boolean)

Purpose: This will determine whether IBeaconService is running in background mode or foreground mode. In foreground mode, scanning will be done continuously. While in background mode, scanning will be done intermittently to save on battery usage.

Where: In MainActivity.onPause(), call it and pass true, because activity is going to background. In MainActivity.onResume(), call it and pass false, because activity is going to foreground.

KSPLocationSettings.setBeaconFeatureEnabled(boolean) and KSPLocationSettings.getBeaconFeatureEnabled(context)

Purpose: User can disable the IBeacon feature by setting this value to false. It will cause KSPMicroLocationService to stop monitoring or ranging beacons. Default value is enabled. This is optional and only works locally.

Where: This is currently done in the DemoApp in the SettingsFragment.

KSPLocationSettings.setGeofenceEnabled(Boolean) and KSPLocationSettings.getGeofenceEnabled(context)

Purpose: User can disable the Geofence feature by setting this value to false. It will cause KSPGeofenceIntentService to stop monitoring geofence. Default value is enabled. This is optional and only works locally.

Where: This is currently done in the DemoApp in the SettingsFragment.