Update configurations at runtime

This example guides you through the following steps:

  • Initialization with Customized Configurations: Learn how to set up the SDK with customized configuration values, tailoring it to your specific requirements and preferences.

  • Updating Configuration Settings at Runtime: Discover how to dynamically modify configuration settings such as LocationConfig, NotificationConfig, and DataTrackingConfig during the execution of your application. This flexibility empowers you to adapt the SDK to changing conditions and user needs in real time.

For all code examples, refer to Asset Tracking Android Code Examples

activity_update_configuration.xml view source

1
<?xml version="1.0" encoding="utf-8"?>
2
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3
xmlns:app="http://schemas.android.com/apk/res-auto"
4
xmlns:tools="http://schemas.android.com/tools"
5
android:layout_width="match_parent"
6
android:layout_height="match_parent"
7
android:orientation="vertical"
8
android:padding="10dp"
9
tools:context=".codeexample.AssetProfileOperations">
10
11
<Button
12
android:id="@+id/update_location_config"
13
android:layout_width="wrap_content"
14
android:layout_height="wrap_content"
15
android:text="@string/update_location_config" />
16
17
<Button
18
android:id="@+id/update_notification_config"
19
android:layout_width="wrap_content"
20
android:layout_height="wrap_content"
21
android:text="@string/update_notification_config" />
22
23
<Button
24
android:id="@+id/update_data_tracking_config"
25
android:layout_width="wrap_content"
26
android:layout_height="wrap_content"
27
android:text="@string/update_data_tracking_config" />
28
29
<TextView
30
android:id="@+id/configuration_detail"
31
android:layout_width="wrap_content"
32
android:layout_height="wrap_content"
33
android:layout_marginTop="10dp" />
34
35
</LinearLayout>

UpdateConfiguration view source

1
class UpdateConfiguration : AppCompatActivity() {
2
private lateinit var updateLocationConfigButton: Button
3
private lateinit var updateNotificationConfigButton: Button
4
private lateinit var updateDataTrackingConfigButton: Button
5
private lateinit var configurationDetailView: TextView
6
7
private lateinit var defaultConfig: DefaultConfig
8
private lateinit var locationConfig: LocationConfig
9
private lateinit var notificationConfig: NotificationConfig
10
private lateinit var dataTrackingConfig: DataTrackingConfig
11
12
var permissionsManager: LocationPermissionsManager? = null
13
private var assetId = ""
14
15
override fun onCreate(savedInstanceState: Bundle?) {
16
super.onCreate(savedInstanceState)
17
setContentView(R.layout.activity_update_configuration)
18
19
// initialize the Asset Tracking SDK
20
initConfigurations()
21
createAsset()
22
23
initView()
24
}
25
26
override fun onDestroy() {
27
super.onDestroy()
28
// add this to avoid blocking other example, could remove in real usage
29
assetTrackingStop()
30
}
31
32
@SuppressLint("SetTextI18n")
33
private fun initView() {
34
configurationDetailView = findViewById(R.id.configuration_detail)
35
36
updateLocationConfigButton = findViewById(R.id.update_location_config)
37
updateLocationConfigButton.setOnClickListener {
38
val locationConfigToChange = LocationConfig(
39
interval = 20000,
40
smallestDisplacement = 20.0f,
41
maxWaitTime = 5000,
42
fastestInterval = 1500,
43
enableStationaryCheck = true
44
)
45
assetTrackingUpdateLocationConfig(locationConfigToChange)
46
47
locationConfig = assetTrackingGetLocationConfig()
48
49
configurationDetailView.text = "location config: " + Gson().toJson(locationConfig)
50
51
}
52
53
updateNotificationConfigButton = findViewById(R.id.update_notification_config)
54
updateNotificationConfigButton.setOnClickListener {
55
val notificationConfigToChange = NotificationConfig(
56
channelId = "NextBillion.ai",
57
channelName = "NextBillion.ai",
58
)
59
assetTrackingUpdateNotificationConfig(notificationConfigToChange)
60
61
notificationConfig = assetTrackingGetNotificationConfig()
62
63
configurationDetailView.text = "notification config: " + Gson().toJson(notificationConfig)
64
}
65
66
updateDataTrackingConfigButton = findViewById(R.id.update_data_tracking_config)
67
updateDataTrackingConfigButton.setOnClickListener {
68
69
val dataTrackingConfigToChange = DataTrackingConfig(
70
baseUrl = "https://api.nextbillion.io",
71
dataUploadingBatchSize = 15,
72
dataUploadingBatchWindow = 30,
73
dataStorageSize = 5000,
74
shouldClearLocalDataWhenCollision = false
75
)
76
assetTrackingUpdateDataTrackingConfig(dataTrackingConfigToChange)
77
78
dataTrackingConfig = assetTrackingGetDataTrackingConfig()
79
configurationDetailView.text = "dataTracking config: " + Gson().toJson(dataTrackingConfig)
80
}
81
}
82
83
84
private fun initConfigurations() {
85
defaultConfig = DefaultConfig(
86
debug = false,
87
enhanceService = true,
88
repeatInterval = 5L,
89
workerEnabled = true,
90
crashRestartEnabled = true,
91
workOnMainThread = true,
92
restartIntent = null
93
)
94
95
// You can either choose the specified tracking mode, or use self-defined
96
locationConfig = LocationConfig(
97
trackingMode = TrackingMode.ACTIVE,
98
maxWaitTime = 10000,
99
fastestInterval = 1000,
100
enableStationaryCheck = false
101
)
102
103
notificationConfig = NotificationConfig(channelId = "Custom.ID", channelName = "Custom.Name")
104
105
dataTrackingConfig = DataTrackingConfig(
106
baseUrl = "https://api.nextbillion.io",
107
dataUploadingBatchSize = 30,
108
dataUploadingBatchWindow = 20,
109
dataStorageSize = 5000,
110
shouldClearLocalDataWhenCollision = true
111
)
112
113
AssetTracking {
114
setDefaultConfig(defaultConfig)
115
setLocationConfig(locationConfig)
116
setNotificationConfig(notificationConfig)
117
setDataTrackingConfig(dataTrackingConfig)
118
}
119
120
initialize("PUT YOUR API KEY HERE")
121
}
122
123
private fun createAsset() {
124
val assetAttributes: Map<String, String> = mapOf("attribute 1" to "test 1", "attribute 2" to "test 2")
125
val assetProfile = AssetProfile.Builder().setCustomId(UUID.randomUUID().toString()).setName("testName")
126
.setDescription("testDescription").setAttributes(assetAttributes).build()
127
128
createNewAsset(assetProfile, object : AssetApiCallback<AssetCreationResponse> {
129
@SuppressLint("SetTextI18n")
130
override fun onSuccess(result: AssetCreationResponse) {
131
assetId = result.data.id
132
Toast.makeText(
133
this@UpdateConfiguration,
134
"create asset successfully with asset id: $assetId",
135
Toast.LENGTH_LONG
136
).show()
137
bindAssetAndStartTracking()
138
}
139
140
override fun onFailure(exception: Exception) {
141
Toast.makeText(
142
this@UpdateConfiguration,
143
"create asset failed with error: " + exception.message,
144
Toast.LENGTH_LONG
145
).show()
146
}
147
})
148
}
149
150
private fun bindAssetAndStartTracking() {
151
bindAsset(assetId, object : AssetApiCallback<Unit> {
152
@SuppressLint("SetTextI18n")
153
override fun onSuccess(result: Unit) {
154
Toast.makeText(
155
this@UpdateConfiguration,
156
String.format(
157
"bind asset successfully with assetId: %s",
158
assetId
159
),
160
Toast.LENGTH_LONG
161
).show()
162
checkPermissionsAndStartTracking()
163
}
164
165
override fun onFailure(exception: Exception) {
166
val exceptionMessage = exception.message ?: ""
167
Toast.makeText(
168
this@UpdateConfiguration,
169
"bind asset failed: $exceptionMessage",
170
Toast.LENGTH_LONG
171
).show()
172
}
173
})
174
}
175
176
private fun checkPermissionsAndStartTracking() {
177
if (LocationPermissionsManager.areAllLocationPermissionGranted(this)) {
178
startTracking()
179
} else if (!LocationPermissionsManager.isLocationServiceEnabled(this)) {
180
showLocationServiceOffDialog()
181
} else {
182
permissionsManager = LocationPermissionsManager(object : LocationPermissionsListener {
183
override fun onExplanationNeeded(permissionsToExplain: List<String>?) {
184
Toast.makeText(
185
this@UpdateConfiguration, "You need to accept location permissions.",
186
Toast.LENGTH_SHORT
187
).show()
188
}
189
190
override fun onPermissionResult(granted: Boolean) {
191
if (granted) {
192
if (LocationPermissionsManager.isBackgroundLocationPermissionGranted(this@UpdateConfiguration)) {
193
startTracking()
194
} else {
195
permissionsManager?.requestBackgroundLocationPermissions(this@UpdateConfiguration)
196
}
197
} else {
198
Toast.makeText(
199
this@UpdateConfiguration, "You need to accept location permissions.$granted",
200
Toast.LENGTH_SHORT
201
).show()
202
}
203
}
204
})
205
permissionsManager?.requestLocationPermissions(this)
206
}
207
}
208
209
@SuppressLint("MissingPermission", "SetTextI18n")
210
fun startTracking() {
211
assetTrackingStart()
212
}
213
214
private fun showLocationServiceOffDialog() {
215
val alertDialogBuilder = AlertDialog.Builder(this)
216
217
alertDialogBuilder.setTitle("Location Services Disabled")
218
alertDialogBuilder.setMessage("To enable location services, please go to Settings > Privacy > Location Services.")
219
220
alertDialogBuilder.setPositiveButton("OK") { dialogInterface: DialogInterface, _: Int ->
221
dialogInterface.dismiss() // Close the dialog
222
}
223
224
val alertDialog = alertDialogBuilder.create()
225
alertDialog.show()
226
}
227
228
}

Upon executing the code example provided above, your app's appearance will resemble the following snippet:

documentation image

Code Highlights

The above code snippet is for an Android activity that demonstrates how to update the configuration of the Asset Tracking SDK. The activity has the following main steps:

  1. Initialize the Asset Tracking SDK.

  2. Create an asset profile.

  3. Bind the asset profile to the device.

  4. Start tracking the asset.

  5. Update the configuration of the Asset Tracking SDK.

The following is a description of each step:

  1. To initialize the Asset Tracking SDK, the activity calls the initialize() method with the API key.

  2. To create an asset profile, the activity creates an AssetProfile object and sets its properties. The AssetProfile object specifies the asset's custom ID, name, description, and attributes.

  3. To bind the asset profile to the device, the activity calls the bindAsset() method with the asset ID.

  4. To start tracking the asset, the activity calls the assetTrackingStart() method.

  5. To update the configuration of the Asset Tracking SDK, the activity calls the following methods:

    1. assetTrackingUpdateLocationConfig(): This method updates the location configuration.

    2. assetTrackingUpdateNotificationConfig(): This method updates the notification configuration.

    3. assetTrackingUpdateDataTrackingConfig(): This method updates the data tracking configuration.

The activity also includes a few helper functions:

  • initConfigurations(): This function initializes the default configuration, location configuration, notification configuration, and data tracking configuration.

  • createAsset(): This function creates an asset profile and binds it to the device.

  • bindAssetAndStartTracking(): This function binds an asset profile to the device and starts tracking the asset.

  • checkPermissionsAndStartTracking(): This function checks for location permissions and starts tracking the asset if they are granted.

  • showLocationServiceOffDialog(): This function shows a dialog to the user if location services are disabled.

© 2024 NextBillion.ai all rights reserved.