Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
* Copyright 2025 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.wear.snippets.com.example.wear.snippets.datalayer

import androidx.activity.ComponentActivity
import com.google.android.gms.tasks.Task
import com.google.android.gms.wearable.DataClient
import com.google.android.gms.wearable.DataEvent
import com.google.android.gms.wearable.DataEventBuffer
import com.google.android.gms.wearable.DataItem
import com.google.android.gms.wearable.DataMapItem
import com.google.android.gms.wearable.PutDataMapRequest
import com.google.android.gms.wearable.PutDataRequest
import com.google.android.gms.wearable.Wearable

class DataLayerActivity : ComponentActivity(), DataClient.OnDataChangedListener {
private val dataClient by lazy { Wearable.getDataClient(this) }
private val messageClient by lazy { Wearable.getMessageClient(this) }
private val capabilityClient by lazy { Wearable.getCapabilityClient(this) }

private var count = 0

override fun onResume() {
super.onResume()
Wearable.getDataClient(this).addListener(this)
}

override fun onPause() {
super.onPause()
Wearable.getDataClient(this).removeListener(this)
}

// [START android_wear_datalayer_increasecounter]
private fun increaseCounter() {
val putDataReq: PutDataRequest = PutDataMapRequest.create("/count").run {
dataMap.putInt(COUNT_KEY, count++)
asPutDataRequest()
}
val putDataTask: Task<DataItem> = dataClient.putDataItem(putDataReq)
}
// [END android_wear_datalayer_increasecounter]

// [START android_wear_datalayer_ondatachangedlistener]
override fun onDataChanged(dataEvents: DataEventBuffer) {

dataEvents.forEach { event ->
// DataItem changed
if (event.type == DataEvent.TYPE_CHANGED) {
event.dataItem.also { item ->
if (item.uri.path?.compareTo("/count") == 0) {
DataMapItem.fromDataItem(item).dataMap.apply {
updateCount(getInt(COUNT_KEY))
}
}
}
} else if (event.type == DataEvent.TYPE_DELETED) {
// DataItem deleted
}
}
}
// [END android_wear_datalayer_ondatachangedlistener]

private fun updateCount(int: Int) {
}
companion object {
private const val COUNT_KEY = "com.example.key.count"
}
}