@@ -21,9 +21,13 @@ import android.util.Log
2121import com.google.android.gms.wearable.DataClient
2222import com.google.android.gms.wearable.DataEvent
2323import com.google.android.gms.wearable.DataEventBuffer
24+ import com.google.android.gms.wearable.DataItem
25+ import com.google.android.gms.wearable.DataItemBuffer
2426import com.google.android.gms.wearable.DataMapItem
27+ import com.google.android.gms.wearable.PutDataRequest
2528import com.google.android.gms.wearable.Wearable
2629import com.google.android.gms.wearable.WearableListenerService
30+ import kotlinx.coroutines.runBlocking
2731
2832private const val TAG = " DataLayerSample"
2933private const val START_ACTIVITY_PATH = " /start-activity"
@@ -107,3 +111,41 @@ class MainActivity : Activity(), DataClient.OnDataChangedListener {
107111 }
108112}
109113// [END android_wear_datalayer_ondatachangedlisteneer]
114+
115+ // [START android_wear_datalayer_mywearablelistenerservice]
116+ class MyWearableListenerService : WearableListenerService () {
117+ val dataClient: DataClient = Wearable .getDataClient(this )
118+
119+ private fun shouldHandleDataItem (nodeId : String , dataItem : DataItem ): Boolean {
120+ // Your logic here
121+ return dataItem.uri.path?.startsWith(" /my_feature_path/" ) == true
122+ }
123+
124+ private fun handleDataItem (nodeId : String , dataItem : DataItem ) {
125+ val data = dataItem.data ? : return
126+ val path = dataItem.uri.path ? : return
127+ // Your logic here
128+ if (data.toString().startsWith(" Please restore" )) {
129+ dataClient.putDataItem(PutDataRequest .create(path).setData(data))
130+ }
131+ }
132+
133+ override fun onNodeMigrated (nodeId : String , archive : DataItemBuffer ) {
134+ val dataItemsToHandle = mutableListOf<DataItem >()
135+
136+ for (dataItem in archive) {
137+ if (shouldHandleDataItem(nodeId, dataItem)) {
138+ dataItemsToHandle.add(dataItem.freeze())
139+ }
140+ }
141+
142+ // Callback stops automatically after 20 seconds of data processing.
143+ // If you think you need more time, delegate to a coroutine or thread.
144+ runBlocking {
145+ for (dataItem in dataItemsToHandle) {
146+ handleDataItem(nodeId, dataItem)
147+ }
148+ }
149+ }
150+ }
151+ // [END android_wear_datalayer_mywearablelistenerservice]
0 commit comments