REST API using NanoHttpd/Retrofit

The simplest and most standard way to interact with an IoT device is to provide a REST API. To do that, we need to include a web server in our things app and implement the handling of the requests. A simple library that helps us to achieve that easily is NanoHttpd. To include it we need to add the following dependency to our things module:

dependencies {    [...]    implementation 'org.nanohttpd:nanohttpd:2.2.0'}

The architecture we will use is quite simple. The activity will create a web server that will notify the requests received via an interface that represents the methods exposed on the API. In our case the interface is:

interface ApiListener {    fun onGetTemperature(): JSONObject    fun onPostLed(request: JSONObject) ...

Get Android Things Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.