|
package <package_name> |
|
|
|
import android.app.Activity |
|
import android.os.Bundle |
|
import android.util.Log |
|
import com.google.android.things.pio.Gpio |
|
import com.google.android.things.pio.GpioCallback |
|
import com.google.android.things.pio.PeripheralManager |
|
import java.io.IOException |
|
|
|
class ButtonEvents : Activity() { |
|
|
|
//Variables |
|
val TAG = "Button Events Activity" |
|
val BUTTON_PIN_NAME = <pin_name> |
|
val manager = PeripheralManager.getInstance() |
|
lateinit var mButtonGpio: Gpio |
|
|
|
override fun onCreate(savedInstanceState: Bundle?) { |
|
super.onCreate(savedInstanceState) |
|
|
|
try { |
|
// Create GPIO connection. |
|
mButtonGpio = manager.openGpio(BUTTON_PIN_NAME) |
|
// Configure as an input. |
|
mButtonGpio.setDirection(Gpio.DIRECTION_IN) |
|
// Enable edge trigger events. |
|
mButtonGpio.setEdgeTriggerType(Gpio.EDGE_FALLING) |
|
// Register an event callback. |
|
mButtonGpio.registerGpioCallback(mCallBack) |
|
} catch (e: IOException) { |
|
Log.e(TAG, "Error on PeripheralIO API", e) |
|
} |
|
} |
|
|
|
override fun onDestroy() { |
|
super.onDestroy() |
|
mButtonGpio.unregisterGpioCallback(mCallBack) |
|
// Close the resource |
|
try { |
|
mButtonGpio.close() |
|
} catch (e: IOException) { |
|
Log.e(TAG, "Error on Peripheral IO API", e) |
|
} |
|
|
|
} |
|
|
|
// Register an event callback. |
|
private val mCallBack = GpioCallback { |
|
Log.i(TAG, "GPIO state changed, button pressed") |
|
// Return true to keep callback active. |
|
true |
|
} |
|
} |