In this page

Simple Asset Tracking

这篇文档目前尚未提供译文,将以原文展示。

This example provides step by step guidance on:

  1. Initializing Configurations with Default Values: Learn how to set up the SDK with default configuration settings, ensuring a straightforward integration process.

  2. Creating and Binding a Simple Asset: Discover how to create and bind an asset within your application, enabling you to associate assets with your tracking system.

  3. Starting Tracking and Uploading Location Data with Default Values: Gain insights into how to initiate tracking and the automatic uploading of location data using default parameters, simplifying the process of monitoring asset locations.

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

activity_simple_tracking.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.SimpleTrackingExample">
10
11   <Button
12       android:id="@+id/start_tracking_simple"
13       android:layout_width="wrap_content"
14       android:layout_height="wrap_content"
15       android:text="@string/start_tracking"
16       />
17
18   <TextView
19       android:id="@+id/asset_id_info"
20       android:layout_marginTop="10dp"
21       android:layout_width="wrap_content"
22       android:layout_height="wrap_content"/>
23
24   <TextView
25       android:id="@+id/tracking_status_simple"
26       android:layout_marginTop="10dp"
27       android:layout_width="wrap_content"
28       android:layout_height="wrap_content"/>
29
30</LinearLayout>

SimpleTrackingExample view source

1class SimpleTrackingExample : AppCompatActivity() {
2    private lateinit var startTrackingButton: Button
3    private lateinit var trackingStatusView: TextView
4    private lateinit var assetIdView: TextView
5
6    var permissionsManager: LocationPermissionsManager? = null
7    private var assetId = ""
8
9    override fun onCreate(savedInstanceState: Bundle?) {
10        super.onCreate(savedInstanceState)
11        setContentView(R.layout.activity_simple_tracking)
12        initView()
13
14        // initialize the Asset Tracking SDK
15         initialize("PUT YOUR API KEY HERE")
16
17        createAsset()
18    }
19
20    override fun onDestroy() {
21        super.onDestroy()
22        // add this to avoid blocking other example, could remove in real usage
23        assetTrackingStop()
24    }
25
26    private fun initView() {
27        startTrackingButton = findViewById(R.id.start_tracking_simple)
28        startTrackingButton.setOnClickListener {
29            bindAssetAndStartTracking()
30        }
31
32        trackingStatusView = findViewById(R.id.tracking_status_simple)
33        assetIdView = findViewById(R.id.asset_id_info)
34    }
35
36    private fun createAsset() {
37        val assetAttributes: Map<String, String> = mapOf("attribute 1" to "test 1", "attribute 2" to "test 2")
38        val assetProfile = AssetProfile.Builder().setCustomId(UUID.randomUUID().toString()).setName("testName")
39            .setDescription("testDescription").setAttributes(assetAttributes).build()
40
41        createNewAsset(assetProfile, object : AssetApiCallback<AssetCreationResponse> {
42            @SuppressLint("SetTextI18n")
43            override fun onSuccess(result: AssetCreationResponse) {
44                assetId = result.data.id
45                Toast.makeText(
46                    this@SimpleTrackingExample,
47                    "create asset successfully with asset id: $assetId",
48                    Toast.LENGTH_LONG
49                ).show()
50
51                assetIdView.text = "current asset id is: $assetId"
52            }
53
54            override fun onFailure(exception: Exception) {
55                Toast.makeText(
56                    this@SimpleTrackingExample,
57                    "create asset failed with error: " + exception.message,
58                    Toast.LENGTH_LONG
59                ).show()
60            }
61        })
62    }
63
64    private fun bindAssetAndStartTracking() {
65        bindAsset(assetId, object : AssetApiCallback<Unit> {
66            @SuppressLint("SetTextI18n")
67            override fun onSuccess(result: Unit) {
68                Toast.makeText(
69                    this@SimpleTrackingExample,
70                    String.format(
71                        "bind asset successfully with assetId: %s",
72                        assetId
73                    ),
74                    Toast.LENGTH_LONG
75                ).show()
76                checkPermissionsAndStartTracking()
77            }
78
79            override fun onFailure(exception: Exception) {
80                val exceptionMessage = exception.message ?: ""
81                Toast.makeText(
82                    this@SimpleTrackingExample,
83                    "bind asset failed: $exceptionMessage",
84                    Toast.LENGTH_LONG
85                ).show()
86            }
87        })
88    }
89
90    private fun checkPermissionsAndStartTracking() {
91        if (LocationPermissionsManager.areAllLocationPermissionGranted(this)) {
92            startTracking()
93        } else if (!LocationPermissionsManager.isLocationServiceEnabled(this)) {
94            showLocationServiceOffDialog()
95        } else {
96            permissionsManager = LocationPermissionsManager(object : LocationPermissionsListener {
97                override fun onExplanationNeeded(permissionsToExplain: List<String>?) {
98                    Toast.makeText(
99                        this@SimpleTrackingExample, "You need to accept location permissions.",
100                        Toast.LENGTH_SHORT
101                    ).show()
102                }
103
104                override fun onPermissionResult(granted: Boolean) {
105                    if (granted) {
106                        if (LocationPermissionsManager.isBackgroundLocationPermissionGranted(this@SimpleTrackingExample)) {
107                            startTracking()
108                        } else {
109                            permissionsManager?.requestBackgroundLocationPermissions(this@SimpleTrackingExample)
110                        }
111                    } else {
112                        Toast.makeText(
113                            this@SimpleTrackingExample, "You need to accept location permissions.$granted",
114                            Toast.LENGTH_SHORT
115                        ).show()
116                    }
117                }
118            })
119            permissionsManager?.requestLocationPermissions(this)
120        }
121    }
122
123    @SuppressLint("MissingPermission", "SetTextI18n")
124    fun startTracking() {
125        assetTrackingStart()
126        trackingStatusView.text = "Asset Tracking is running"
127    }
128
129    private fun showLocationServiceOffDialog() {
130        val alertDialogBuilder = AlertDialog.Builder(this)
131
132        alertDialogBuilder.setTitle("Location Services Disabled")
133        alertDialogBuilder.setMessage("To enable location services, please go to Settings > Privacy > Location Services.")
134
135        alertDialogBuilder.setPositiveButton("OK") { dialogInterface: DialogInterface, _: Int ->
136            dialogInterface.dismiss() // Close the dialog
137        }
138
139        val alertDialog = alertDialogBuilder.create()
140        alertDialog.show()
141    }
142
143}

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

Code Highlights

The above code snippet is for an Android activity that demonstrates how to start tracking an asset using the Asset Tracking SDK. The activity has the following main steps:

  1. Initialize the Asset Tracking SDK.

  2. Create an asset.

  3. Bind the asset to the device.

  4. Check for location permissions and start tracking.

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, 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 to the device, the activity calls the bindAsset() method with the asset ID.

  4. To check for location permissions and start tracking, the activity calls the checkPermissionsAndStartTracking() method. This method first checks if all location permissions are granted. If they are, the method starts tracking the asset. If they are not granted, the method shows a dialog to the user asking them to grant the permissions.

The code snippet also includes a few helper functions:

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

  2. startTracking(): This function starts tracking and uploading the location data of the asset.

没找到你要找的内容?