Peripheral lifecycle

Whenever we want to use a peripheral, we need to get access to it before we can do anything with it. This is done using the open method that all peripheral classes have. Opening a peripheral gives us exclusive control over it and therefore it can not be opened if it is already open by another app. The operating system will throw an Exception if the peripheral is already in use.

As you can imagine, this also means that we need to release the peripheral once we are done with it. This is done by invoking the close method.

Unless it is a special case, you should open all your peripherals inside onCreate and close them inside onDestroy.

In general, you will want to open the peripherals inside onCreate and close them inside onDestroy, so you can use them anytime along the lifecycle of the activity. You can, however, open, interact, and close them in a single block of code. It is less efficient if you are going to access them several times, but in some cases—such as single use—it could be preferred since the peripheral is held by the activity for just the minimum time needed.

There is also the concept of AutoCloseable, which is an interface that all the peripherals implement. It helps the system identify components that should be closed and it does so whenever the activity is destroyed.

AutoCloseable peripherals should close automatically whenever they are deallocated, but it is still recommended to call close on all peripherals inside onDestroy to enforce clarity and consistency.
..................Content has been hidden....................

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