Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Getting started with Amazon Sidewalk Mobile Android SDK

Use this document to get started with Amazon Sidewalk Mobile Android SDK. This document walks you through how to integrate Amazon Sidewalk Mobile Android SDK into your Android apps.

Topics

Related

Prerequisites

To complete this getting started tutorial, you first need the following:

  • Minimum API level 23 (Android 6.0) or higher
  • Amazon Sidewalk MCU SDK version 1.14

Set up your app

The Amazon Sidewalk Mobile Android SDK provides APIs for Android apps. Using the SDK, you can build Android apps that interact with the Amazon Sidewalk network.This document shows you how to set up the dependency of Amazon Sidewalk Mobile Android SDK in your app. Once you set up your app, you write your own code with Amazon Sidewalk Mobile Android SDK to scan and register devices onto on the Amazon Sidewalk network.

Follow the instructions to complete the setup:

Step 1: Integrate Login with Amazon into your app

Sidewalk devices can be attached to an Amazon account.

In order to protect user data integrity and to provide a consistent user experience, interactions with the Amazon Sidewalk network requires a user access token from Login with Amazon (LWA).

Before you begin adding the Amazon Sidewalk Mobile SDK to your app, follow the steps to integrate LWA into your app:

Obtain your Android API key

Follow all the instructions here to set up a security profile and get your Android API key. The Consent Privacy Notice URL field you set in the security profile will be shown at the bottom of the consent screen on your mobile app, with the link being “[Security Profile Name] Privacy”. The Consent Logo Image is optional. If provided, it will be shown at the top of the consent screen. You will also be able to see these in https://www.amazon.com/ap/adam?ref_=ya_d_l_iba

Integrate LWA into your app

  1. Follow the instructions here to download the LWA SDK for Android.

  2. Follow the instructions here to set up LWA for your app. You can skip the “Create a New Project in Android Studio” section if you already have a project.

Use LWA to login and logout a user

Follow the instructions here to implement user login and logout. You can skip the “Fetch User Profile Data” section. When calling AuthorizationManager.authorize(), use the sidewalk::manage_endpoint scope.

AuthorizationManager.authorize(
    AuthorizeRequest.Builder(requestContext)
        .addScopes(ScopeFactory.scopeNamed("sidewalk::manage_endpoint"))
        .shouldReturnUserData(false)
        .build()
)

Remember to call Sidewalk.clearAccountCache() when the user logs out. This document shows you how to integrate Amazon Sidewalk Mobile Android SDK into your app. Amazon Sidewalk only requires a LWA user access token and does not require you to integrate your existing account system with LWA. You can skip the “Integrating with Your Account System” section in the LWA documentation.

Note
Amazon Sidewalk only requires a LWA user access token and does not require you to integrate your existing account system with LWA. You can skip the “Integrating with Your Account System” section in the LWA documentation.

Step 2: Add Sidewalk Mobile Android SDK to your app

Amazon Sidewalk Mobile Android SDK is distributed as an Apache Maven package under maven central. With mavenCentral() config in project level Gradle file, we can add the dependency for Amazon Sidewalk Mobile Android SDK In your app-level Gradle file directly. You can find all released versions in Release Notes.

build.gradle.kts

// project-level build.gradle.kts
allprojects {
    repositories {
        ...
        mavenCentral()
    }
}
 
// app-level build.gradle.kts
dependencies {
  // ...
 
  // Add the dependency for the Amazon Sidewalk Mobile Android SDK
  implementation("com.amazon.sidewalk:mobile-sdk:[Sidewalk Mobile SDK Version]")
}

build.gradle.kts

// project-level build.gradle.kts
allprojects {
    repositories {
        ...
        mavenCentral()
    }
}
 
// app-level build.gradle.kts
dependencies {
  // ...
 
  // Add the dependency for the Amazon Sidewalk Mobile Android SDK
  implementation("com.amazon.sidewalk:mobile-sdk:[Sidewalk Mobile SDK Version]")
}

After adding the dependency, sync your Android project.

Development Environment
Ensure that you are using the Android Gradle plugin version 7.0 or later in Android Studio and set minimum API level to 23 or higher.

Add permissions

Amazon Sidewalk Mobile Android SDK uses Bluetooth to interact with devices.

Follow the code snippet below to add user permission for Bluetooth. For more information, visit Android developers guides for Bluetooth permissions.

<manifest ... >
    ...
    <uses-permission
        android:name="android.permission.BLUETOOTH"
        android:maxSdkVersion="30" />
    <uses-permission
        android:name="android.permission.BLUETOOTH_ADMIN"
        android:maxSdkVersion="30" />
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    ...
</manifest>

Request permissions

Before calling Amazon Sidewalk APIs, you will have to request necessary permissions from the user. The following code snippets show you how to use Activity Result APIs to request permissions.

First, create a ActivityResultLauncher for requesting location permission on Android 11 and lower.

private val locationPermissionsLauncher =
    registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
        if (permissions.values.any { !it }) {
            // Location permission denied.
        }
    }
 
private fun requestLocationPermissionIfNeeded() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
        locationPermissionsLauncher.launch(
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION
            )
        )
    }
}

Second, create another two ActivityResultLauncher for handling a set of Bluetooth permissions according to the Android version.

private val bleRuntimePermissionsLauncher =
    registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
        if (permissions.values.all { it }) {
            requestLocationPermissionIfNeeded()
        } else {
            // BLE permission denied.
        }
    }
 
private val bluetoothEnableLauncher =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == AppCompatActivity.RESULT_OK) {
            requestLocationPermissionIfNeeded()
        } else {
            // BLE permission denied.
        }
    }
 
private fun requestBlePermissions() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        bleRuntimePermissionsLauncher.launch(
            arrayOf(
                Manifest.permission.BLUETOOTH_SCAN,
                Manifest.permission.BLUETOOTH_CONNECT
            )
        )
    } else {
        val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        bluetoothEnableLauncher.launch(enableBtIntent)
    }
}

Finally, request for permissions before calling Amazon Sidewalk API. For more information and best practices, see Android developers guides for requesting permissions.

class MyFragment : Fragment() {
 
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
 
        requestBlePermissions()
    }
}

The full permission handling flow can be found in the sample app.

Step 3: Write your Amazon Sidewalk project

Write your Amazon Sidewalk project using Amazon Sidewalk Mobile Android SDK. This document shows you how to use Amazon Sidewalk Mobile Android SDK to register a device after user login.

Implement the SidewalkAuthProvider

First, implement SidewalkAuthProvider to provide a LWA user access token to the Amazon Sidewalk Mobile Android SDK. When asking for a user access token from LWA, use the sidewalk::manage_endpoint scope, it is the same scope you use when user logs in.

val sidewalkAuthProvider = object : SidewalkAuthProvider {
 
    override suspend fun getToken(): SidewalkResult<String> = suspendCoroutine { continuation ->
        val scopes = arrayOf(ScopeFactory.scopeNamed("sidewalk::manage_endpoint"))
 
        AuthorizationManager.getToken(
            context,
            scopes,
            object : Listener<AuthorizeResult, AuthError> {
                override fun onSuccess(result: AuthorizeResult) {
                    result.accessToken?.let {
                        // Success
                        continuation.resume(SidewalkResult.Success(it))
                    } ?: run {
                        // User is not logged in.
                        continuation.resume(SidewalkResult.Failure())
                    }
                }
 
                override fun onError(ae: AuthError) {
                    // Error
                    continuation.resume(SidewalkResult.Failure(ae))
                }
            }
        )
    }
}

Amazon Sidewalk Mobile Android SDK API will internally call SidewalkAuthProvider.getToken() anytime when needed.

Create a Sidewalk

Create a Sidewalk with a SidewalkAuthProvider instance.

val sidewalk = Sidewalk(context, sidewalkAuthProvider)

Note
Use the same Sidewalk instance during the lifecycle of Application. You can use dependency injection (DI) to reuse the same Sidewalk instance across your app. The sample app uses Hilt for dependency injection. See Dependency injection in Android for more information.

Scan and get a SidewalkDevice

Call Sidewalk.scan() to scan for nearby devices. The method returns a flow of SidewalkDevice.

class MyViewModel : ViewModel() {
 
    private val scanList = mutableListOf<SidewalkDevice>()
 
    fun scan () {
        viewModelScope.launch {
            scanList.clear()
 
            sidewalk.scan().collect { result ->
                when (result) {
                    is SidewalkResult.Success -> {
                        // A `SidewalkDevice` is discovered.
                        scanList.add(result.value)
                    }
                    is SidewalkResult.Failure -> {
                        // Error
                    }
                }
            }
        }
    }
}

Register Amazon Sidewalk Device

Call Sidewalk.registerDevice() with a Sidewalk Manufacturing Serial Number(SMSN) string to register a device to the user. Sidewalk.registerDevice() internally calls SidewalkAuthProvider.getToken() to get the user access token.

class MyViewModel : ViewModel() {
 
    fun registerDevice(smsn: String) {
        viewModelScope.launch {
            val result = sidewalk.registerDevice(smsn)            
            when (result) {
                is SidewalkResult.Success -> {
                    // Device registered!
                }
                is SidewalkResult.Failure -> {
                    // Error
                }
            }
        }
    }
}

Get logs from Amazon Sidewalk Mobile SDK

Set Sidewalk.logger to an object that implements SidewalkLogging with the log(sidewalkLogLevel: SidewalkLogLevel, message: String) function.

Sidewalk.logger = SidewalkLogging { sidewalkLogLevel, message ->
    // Save message to a file accoring to log level for further troubleshooting.
}

Note
Amazon Sidewalk Mobile Android SDK also logs the message with “SidewalkSDKAndroid” tag, so you might need to integrate logger only for additional purpose such as saving logs to a file.

Step 4: Build and run the app

Now you can build and run your app to login and logout a user, scan and register devices. Before running the app, remember to turn on bluetooth on the phone. Also, do not forget to call Sidewalk.clearAccountCache() when the user logs out.


Congratulations! Now that you have the basics down, you can start your own journey or check out the sample app.

Please check the Amazon and Ring account linking limitation from here before you start registering device with Amazon Sidewalk Mobile SDK.
Make sure to inform your customer about the action required.

Run the sample app

Step 1: Download the sample app

Clone Android sample app from GitHub https://github.com/amzn/amazon-sidewalk-android-samples to a directory on your hard drive.

Step 2: Set up Login with Amazon

Follow the steps in Integrate Login with Amazon into your app to obtain your Android API key and integrate LWA into the sample app.

Step 3: Run the sample app

You can now compile and run the sample app. The sample app demonstrates the following features:

  • Login and logout users with LWA SDK.
  • Scan nearby Amazon Sidewalk devices.
  • Register and unregister Amazon Sidewalk devices.
  • Establish a secure connection with a device.

Back to top

©2023 Amazon.com, Inc. or its affiliates (collectively, “Amazon”). All Rights Reserved.