Implementation

Prepare your Service

Android SDK requires a foreground service to be running in the background (if needed) to be able to audio recognition. The service is responsible for the following:

RecognitionService.kt

As a foreground service code has many customizable parts, we recommend you to copy the code from the example app and modify it to your needs.

Setup notification for foreground service with own notification title, body and icon.

fun setupNotification() {
    val notificationIntent = Intent(this, MainActivity::class.java)
    val pendingIntent = PendingIntent.getActivity(
        this,
        0,
        notificationIntent,
        PendingIntent.FLAG_IMMUTABLE
    )

    val channel = NotificationChannel(
        CHANNEL_ID,
        CHANNEL_NAME,
        NotificationManager.IMPORTANCE_DEFAULT
    )
    (getSystemService(NOTIFICATION_SERVICE) as NotificationManager)
        .createNotificationChannel(channel)
    val builder = NotificationCompat.Builder(this, CHANNEL_ID)
    builder.setSmallIcon(R.drawable.ic_sori_service)
        .setContentTitle(notificationTitle)
        .setContentText(notificationBody)
        .setContentIntent(pendingIntent)
    startForeground(NOTIF_DETECT, builder.build())
}

Implement your listener

ISoriListener interface defines the callback methods that will be called when the audio recognition is started, stopped, and when the result is received.

Please refer to the following example file:

SoriListener.kt

The code shows how to update the materials to be recognized from server on onConnected event.

In many cases, the onDetected event is needed by UI to update the detected materials.

class EventHandler : SoriListener() {
    override fun onDetected(res: DetectResponse) {
        super.onDetected(res)
        // add result to items state
        items.value = items.value + res
        // or show toast
        Toast.makeText(
            cxt, "Detected: ${res.result.title}",
            Toast.LENGTH_SHORT
        ).show()
        // or show dialog.. whatever you want
    }

    override fun onConnected() {
        super.onConnected()
        setIsRunning(true)  // change recognition indicator state
    }
}