In this last step, we will learn how to close the connection with a GPIO pin. This is an important step because in this way, we free the resources and remove all the listeners we added to the GPIO pins.
An Android Things app has a life cycle very similar to an Android app. The place where we implement these actions is the Activity onDestroy method. In this method we have to:
- Remove all the listeners attached to the GPIO pins
- Close the connection to the GPIO pins
So, open MainActivity.java again and look for the onDestroy method and modify it:
@Override
protected void onDestroy()
{ super.onDestroy(); Log.d(TAG, "onDestroy");
if (gpioPin != null) {
gpioPin.unregisterGpioCallback(sensorCallback);
try {
gpioPin.close(); gpioPin = null;
}
catch(Exception e) {}
}
}