Get AssetTrackingCallback

This example will guide you through the following steps:

  • Initialization with Default Configurations: Learn how to set up the SDK with default configuration values, simplifying the integration process.

  • Creating, Binding, and Initiating Tracking for a Simple Asset: Discover how to create an asset, bind it to your application, and commence tracking. This sequence of actions enables you to monitor asset locations effectively.

  • Receiving AssetTrackingCallback in Your Activities: Gain insight into handling AssetTrackingCallback within your activities, ensuring that you can seamlessly manage and respond to asset-tracking events.

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

activity_get_asset_callback.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.GetAssetCallback">
10
11
<LinearLayout
12
android:layout_width="wrap_content"
13
android:layout_height="wrap_content">
14
15
<Button
16
android:id="@+id/callback_start_tracking"
17
android:layout_width="wrap_content"
18
android:layout_height="wrap_content"
19
android:text="@string/start_tracking" />
20
21
<Button
22
android:id="@+id/callback_stop_tracking"
23
android:layout_width="wrap_content"
24
android:layout_height="wrap_content"
25
android:layout_marginLeft="10dp"
26
android:text="@string/stop_tracking" />
27
28
</LinearLayout>
29
30
31
<TextView
32
android:id="@+id/callback_is_stop_tracking"
33
android:layout_width="wrap_content"
34
android:layout_height="wrap_content"
35
android:layout_marginTop="10dp" />
36
37
<TextView
38
android:id="@+id/callback_location_info"
39
android:layout_width="wrap_content"
40
android:layout_height="wrap_content"
41
android:layout_marginTop="20dp" />
42
43
</LinearLayout>

GetAssetCallback view source

1
class GetAssetCallback : AppCompatActivity(), AssetTrackingCallBack {
2
private lateinit var startTrackingButton: Button
3
private lateinit var stopTrackingButton: Button
4
private lateinit var trackingStatusView: TextView
5
private lateinit var locationInfoView: TextView
6
7
var permissionsManager: LocationPermissionsManager? = null
8
private var assetId = ""
9
10
override fun onCreate(savedInstanceState: Bundle?) {
11
super.onCreate(savedInstanceState)
12
setContentView(R.layout.activity_get_asset_callback)
13
14
// initialize the Asset Tracking SDK
15
initialize("PUT YOUR API KEY HERE")
16
assetTrackingAddCallback(this)
17
18
createAndBindAsset()
19
initView()
20
}
21
22
private fun initView() {
23
startTrackingButton = findViewById(R.id.callback_start_tracking)
24
startTrackingButton.setOnClickListener {
25
checkPermissionsAndStartTracking()
26
}
27
28
stopTrackingButton = findViewById(R.id.callback_stop_tracking)
29
stopTrackingButton.setOnClickListener {
30
assetTrackingStop()
31
}
32
33
trackingStatusView = findViewById(R.id.callback_is_stop_tracking)
34
locationInfoView = findViewById(R.id.callback_location_info)
35
}
36
37
override fun onDestroy() {
38
super.onDestroy()
39
assetTrackingRemoveCallback(this)
40
41
// add this to avoid blocking other example, could remove in real usage
42
assetTrackingStop()
43
}
44
45
@SuppressLint("SetTextI18n")
46
override fun onLocationSuccess(location: Location) {
47
locationInfoView.text = """
48
--------- Location Info ---------
49
Provider: ${location.provider}
50
Latitude: ${location.latitude}
51
Longitude: ${location.longitude}
52
Altitude: ${location.altitude}
53
Accuracy: ${location.accuracy}
54
speed:${location.speed}
55
Bearing: ${location.bearing}
56
Time: ${location.time}
57
""".trimIndent()
58
}
59
60
override fun onLocationFailure(exception: Exception) {
61
locationInfoView.text = exception.message
62
}
63
64
@SuppressLint("SetTextI18n")
65
override fun onTrackingStart(assetId: String) {
66
trackingStatusView.text = "Asset Tracking is ON"
67
}
68
69
@SuppressLint("SetTextI18n")
70
override fun onTrackingStop(assetId: String, trackingDisableType: TrackingDisableType) {
71
trackingStatusView.text = "Asset Tracking is OFF"
72
locationInfoView.text = ""
73
}
74
75
private fun createAndBindAsset() {
76
val assetAttributes: Map<String, String> = mapOf("attribute 1" to "test 1", "attribute 2" to "test 2")
77
val assetProfile = AssetProfile.Builder().setCustomId(UUID.randomUUID().toString()).setName("testName")
78
.setDescription("testDescription").setAttributes(assetAttributes).build()
79
80
createNewAsset(assetProfile, object : AssetApiCallback<AssetCreationResponse> {
81
@SuppressLint("SetTextI18n")
82
override fun onSuccess(result: AssetCreationResponse) {
83
assetId = result.data.id
84
Toast.makeText(
85
this@GetAssetCallback,
86
"create asset successfully with asset id: $assetId",
87
Toast.LENGTH_LONG
88
).show()
89
90
onBindAsset()
91
}
92
93
override fun onFailure(exception: Exception) {
94
Toast.makeText(
95
this@GetAssetCallback,
96
"create asset failed with error: " + exception.message,
97
Toast.LENGTH_LONG
98
).show()
99
}
100
})
101
}
102
103
private fun onBindAsset() {
104
bindAsset(assetId, object : AssetApiCallback<Unit> {
105
@SuppressLint("SetTextI18n")
106
override fun onSuccess(result: Unit) {
107
Toast.makeText(
108
this@GetAssetCallback,
109
String.format(
110
"bind asset successfully with assetId: %s",
111
assetId
112
),
113
Toast.LENGTH_LONG
114
).show()
115
}
116
117
override fun onFailure(exception: Exception) {
118
val exceptionMessage = exception.message ?: ""
119
Toast.makeText(
120
this@GetAssetCallback,
121
"bind asset failed: $exceptionMessage",
122
Toast.LENGTH_LONG
123
).show()
124
}
125
})
126
}
127
128
@SuppressLint("MissingPermission")
129
private fun checkPermissionsAndStartTracking() {
130
if (LocationPermissionsManager.areAllLocationPermissionGranted(this)) {
131
assetTrackingStart()
132
} else if (!LocationPermissionsManager.isLocationServiceEnabled(this)) {
133
showLocationServiceOffDialog()
134
} else {
135
permissionsManager = LocationPermissionsManager(object : LocationPermissionsListener {
136
override fun onExplanationNeeded(permissionsToExplain: List<String>?) {
137
Toast.makeText(
138
this@GetAssetCallback, "You need to accept location permissions.",
139
Toast.LENGTH_SHORT
140
).show()
141
}
142
143
override fun onPermissionResult(granted: Boolean) {
144
if (granted) {
145
if (LocationPermissionsManager.isBackgroundLocationPermissionGranted(this@GetAssetCallback)) {
146
assetTrackingStart()
147
} else {
148
permissionsManager?.requestBackgroundLocationPermissions(this@GetAssetCallback)
149
}
150
} else {
151
Toast.makeText(
152
this@GetAssetCallback, "You need to accept location permissions.$granted",
153
Toast.LENGTH_SHORT
154
).show()
155
}
156
}
157
})
158
permissionsManager?.requestLocationPermissions(this)
159
}
160
}
161
162
private fun showLocationServiceOffDialog() {
163
val alertDialogBuilder = AlertDialog.Builder(this)
164
165
alertDialogBuilder.setTitle("Location Services Disabled")
166
alertDialogBuilder.setMessage("To enable location services, please go to Settings > Privacy > Location Services.")
167
168
alertDialogBuilder.setPositiveButton("OK") { dialogInterface: DialogInterface, _: Int ->
169
dialogInterface.dismiss() // Close the dialog
170
}
171
172
val alertDialog = alertDialogBuilder.create()
173
alertDialog.show()
174
}
175
}

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 receive asset tracking callbacks using 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. Receive asset tracking callbacks.

The following is a description of each step:

  1. To initialize the Asset Tracking SDK, the activity calls the initialize() method with your 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 receive asset tracking callbacks, the activity implements the AssetTrackingCallBack interface and overrides the following methods:

    1. onLocationSuccess(): This method is called when the asset's location is updated.

    2. onLocationFailure(): This method is called when the asset's location fails to be updated.

    3. onTrackingStart(): This method is called when asset tracking is started.

    4. onTrackingStop(): This method is called when asset tracking is stopped.

The activity also includes a few helper functions:

  • createAndBindAsset(): This function creates an asset profile, binds it 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.