override fun onResourcesRequest()

in WearTilesKotlin/app/src/main/java/com/example/wear/tiles/messaging/MessagingTileService.kt [116:169]


    override fun onResourcesRequest(
        requestParams: ResourcesRequest
    ): ListenableFuture<Resources> = serviceScope.future {
        val density = requestParams.deviceParameters!!.screenDensity
        val circleSizePx = (CIRCLE_SIZE * density).roundToInt()
        val contacts = MessagingRepo.getFavoriteContacts()
        Resources.Builder()
            .setVersion(RESOURCES_VERSION)
            .apply {
                // Add the scaled & cropped avatar images
                contacts
                    .mapNotNull { contact ->
                        // Only create a resource for contacts with an associated avatar
                        contact.avatarRes?.let {
                            val drawable = ContextCompat.getDrawable(
                                this@MessagingTileService,
                                contact.avatarRes
                            )
                            // Create a small cropped avatar
                            val bitmap = (drawable as BitmapDrawable).bitmap.croppedCircle(
                                circleSizePx
                            )
                            val bitmapData = ByteBuffer.allocate(bitmap.byteCount).apply {
                                bitmap.copyPixelsToBuffer(this)
                            }.array()
                            // Link the contact's identifier to an image resource
                            contact.id to ImageResource.Builder()
                                .setInlineResource(
                                    InlineImageResource.Builder()
                                        .setData(bitmapData)
                                        .setWidthPx(circleSizePx)
                                        .setHeightPx(circleSizePx)
                                        .setFormat(ResourceBuilders.IMAGE_FORMAT_RGB_565)
                                        .build()
                                )
                                .build()
                        }
                    }.forEach { (id, imageResource) ->
                        // Add each created image resource to the list
                        addIdToImageMapping("$ID_CONTACT_PREFIX$id", imageResource)
                    }
            }
            .addIdToImageMapping(
                ID_IC_SEARCH,
                ImageResource.Builder()
                    .setAndroidResourceByResId(
                        AndroidImageResourceByResId.Builder()
                            .setResourceId(R.drawable.ic_search)
                            .build()
                    )
                    .build()
            )
            .build()
    }