Skip to content

Custom Commands in Android

Registering a Custom Command Handler

To begin, register a custom command handler using the setCommandHandler method provided by EZPush. Create a custom command handler class by extending CommandHandler<T> and implement its methods.

Example: Registering a Custom Command Handler

// Register a custom command handler for the "CLEAR_CACHE" command type
EZPush.setCommandHandler("CLEAR_CACHE", ClearCacheCommand(this))

Creating a Custom Command Handler Class

A custom command handler class is responsible for converting the raw command payload into usable data and defining the action to be taken when the command is received.

Example: Creating a Custom Command Handler Class

class ClearCacheCommand(private val context: Context) : CommandHandler<ClearCacheMessage>() {
    override fun converter(json: String): ClearCacheMessage = Json.decodeFromString(json)

    override fun handle(message: ClearCacheMessage) {
        // Clear the cache directory
        context.cacheDir.listFiles()?.forEach {
            it.deleteOnExit()
        }
    }
}

Custom Data Structure

Define a custom data structure to represent the deserialized command payload. Annotate the data structure with @Serializable to enable JSON serialization and deserialization.

Example: Defining a Custom Data Structure

@Serializable
data class ClearCacheMessage(val randomData: Int)

Advanced Customization

For more advanced use cases, extend and tailor custom command handlers to suit your application's specific needs. Customize the action performed based on the received command.