Activity code

We can see that the Activity has just two methods, onCreate and onDestroy.

class MainActivity : Activity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}

override fun onDestroy() {
super.onDestroy()
}
}

It is noticeable that both methods are empty; while we are used to setting the layout using setContentView on standard Android applications, that code is not there. The explanation is, one again, that displays are optional on Android Things and, therefore, the creation of a layout is optional.

The second interesting point is that there are two methods. This is meant to enforce the lifecycle of peripherals.

The recommended way to work with peripherals is to open them inside onCreate, keep a reference to use them along the app, and close and release them inside onDestroy. Remember, peripherals are hardware that is still on once your application finishes, so if one app leaves them in a particular state, you’ll find them in the same state. If an app does not release them, you may not be able to open them and get an IOException.

We will place the initialization of peripherals inside onCreate and we will release them inside onDestroy.

You can, however, open a peripheral, perform some operations with it, and close it straight away. It is less efficient but, in certain cases, can be handy.

Most peripheral drivers implement AutoCloseable, so they will close themselves even if you forget to do so once the application is destroyed, but it is best to stick to the recommended practices.

Many community drivers have not been updated to fix the breaking changes on Android Things Developer Preview 7 and 8.

Throughout this book, we will be using drivers from the Google-maintained contrib-drivers repository and also from other community-maintained ones, although most will be from PlattyThings. On Android Things Developer Preview 7 and 8, breaking changes were introduced to the SDK, and many community drivers have not been updated to the latest version. I have made that repository to ensure that all the drivers work on Android Things 1.0.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.150.163