overridefunonDataChanged(dataEvents:DataEventBuffer){dataEvents.filter{it.type==DataEvent.TYPE_CHANGED && it.dataItem.uri.path=="/image"}.forEach{event->
valbitmap:Bitmap? =DataMapItem.fromDataItem(event.dataItem).dataMap.getAsset("profileImage").let{asset->loadBitmapFromAsset(asset)}// Do something with the bitmap}}funloadBitmapFromAsset(asset:Asset):Bitmap? {// Convert asset into a file descriptor and block until it's readyvalassetInputStream:InputStream? =Tasks.await(Wearable.getDataClient(context).getFdForAsset(asset))?.inputStreamreturnassetInputStream?.let{inputStream->
// Decode the stream into a bitmapBitmapFactory.decodeStream(inputStream)}?:run{Log.w(TAG,"Requested an unknown Asset.")null}}
Java
@OverridepublicvoidonDataChanged(DataEventBufferdataEvents){for(DataEventevent:dataEvents){if(event.getType()==DataEvent.TYPE_CHANGED&&
event.getDataItem().getUri().getPath().equals("/image")){DataMapItemdataMapItem=DataMapItem.fromDataItem(event.getDataItem());AssetprofileAsset=dataMapItem.getDataMap().getAsset("profileImage");Bitmapbitmap=loadBitmapFromAsset(profileAsset);// Do something with the bitmap}}}publicBitmaploadBitmapFromAsset(Assetasset){if(asset==null){thrownewIllegalArgumentException("Asset must be non-null");}// Convert asset into a file descriptor and block until it's readyInputStreamassetInputStream=Tasks.await(Wearable.getDataClient(context).getFdForAsset(asset)).getInputStream();if(assetInputStream==null){Log.w(TAG,"Requested an unknown Asset.");returnnull;}// Decode the stream into a bitmapreturnBitmapFactory.decodeStream(assetInputStream);}
[null,null,["上次更新時間:2025-08-17 (世界標準時間)。"],[],[],null,["# Sync data\n\nThis document describes how to synchronize data between a Wear OS device and a\nhandheld device.\n\nSend and sync data directly from the network\n--------------------------------------------\n\nBuild Wear OS apps to [communicate directly with the network](/training/wearables/data-layer/network-access). Use the same\nAPIs that you use for mobile development, but keep some Wear-OS-specific\ndifferences in mind.\n\nSynchronize data using the Wear OS Data Layer API\n-------------------------------------------------\n\nA `DataClient` exposes an API for components to read or write to a `DataItem` or\n`Asset`.\n| **Note:** The class is meant to transfer data and not serve as a storage mechanism. Create your own copy of the data that your app can access, such as in a [Room\n| database](/training/data-storage/room).\n\nIt's possible to set data items and assets while not connected to any devices.\nThey're synchronized when the devices establish a network connection. This data\nis private to your app and is only accessible to your app on other devices.\n\n- A `DataItem` is synchronized across all devices in a Wear OS network.\n They're generally small in size.\n\n | **Note:** When an app is uninstalled on the phone, data items and assets are reset.\n- Use an `Asset` to transfer a larger object, such as an image. The system\n keeps track of which assets have already been transferred and performs\n deduplication automatically.\n\n### Listen for events in services\n\nExtend the [`WearableListenerService`](https://developers.google.com/android/reference/com/google/android/gms/wearable/WearableListenerService) class. The system manages the\nlifecycle of the base `WearableListenerService`, binding to the service when it\nneeds to send data items or messages and unbinding the service when no work is\nneeded.\n\n### Listen for events in activities\n\nImplement the [`OnDataChangedListener`](https://developers.google.com/android/reference/com/google/android/gms/wearable/DataClient.OnDataChangedListener) interface. Use this interface instead\nof a `WearableListenerService` when you want to listen for changes only when the\nuser is actively using your app.\n\nTransfer data\n-------------\n\nTo send binary large objects over the Bluetooth transport, such as a voice recording\nfrom another device, you can attach an\n[`Asset`](https://developers.google.com/android/reference/com/google/android/gms/wearable/Asset) to a data item and then put the data item into the replicated datastore.\n|\n| **Note:** The Data Layer API can send messages and synchronize data only with Android phones or\n| Wear OS watches. If a Wear OS device is paired with an iOS device, the Data Layer\n| API won't work.\n|\n|\n| For this reason, don't use the Data Layer API as the primary way to\n| communicate with a network. Instead, follow the same pattern in your Wear app as in a\n| mobile app---with some minor differences, as described in\n| [Network access and sync on Wear OS](/training/wearables/data-layer/network-access).\n\nAssets automatically handle caching of data to prevent retransmission and\nto conserve Bluetooth bandwidth.\nA common pattern is for a handheld app to download an image, shrink it to an appropriate size\nfor display on the wearable, and transmit it to the wearable app as an asset. The following examples\ndemonstrate this pattern.\n\n\n**Note:** Although the size of data items is theoretically limited to 100 KB, in practice larger data items can be used. For\nlarger data items, separate data by unique paths and avoid\nusing a single path for all data. Transferring large assets affects the user experience in many\ncases, so test your apps to help ensure that they perform well when transferring large assets.\n\n### Transfer an asset\n\nCreate the asset using one of the `create...()` methods in the\n[`Asset`](https://developers.google.com/android/reference/com/google/android/gms/wearable/Asset.html) class.\nConvert a bitmap to a byte stream and then call\n[`createFromBytes()`](https://developers.google.com/android/reference/com/google/android/gms/wearable/Asset.html#createFromBytes(byte[]))\nto create the asset, as shown in the following sample. \n\n### Kotlin\n\n```kotlin\nprivate fun createAssetFromBitmap(bitmap: Bitmap): Asset =\n ByteArrayOutputStream().let { byteStream -\u003e\n bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteStream)\n Asset.createFromBytes(byteStream.toByteArray())\n }\n```\n\n### Java\n\n```java\nprivate static Asset createAssetFromBitmap(Bitmap bitmap) {\n final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();\n bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteStream);\n return Asset.createFromBytes(byteStream.toByteArray());\n}\n```\n\nNext, attach the asset to a data item with the `putAsset()` method in\n[`DataMap`](https://developers.google.com/android/reference/com/google/android/gms/wearable/DataMap.html) or\n[`PutDataRequest`](https://developers.google.com/android/reference/com/google/android/gms/wearable/PutDataRequest.html). Then put the data item into the datastore using the\n[`putDataItem()`](https://developers.google.com/android/reference/com/google/android/gms/wearable/DataApi.html#putDataItem(com.google.android.gms.common.api.GoogleApiClient, com.google.android.gms.wearable.PutDataRequest)) method, as shown in the following samples.\n\nThe following sample uses `PutDataRequest`: \n\n### Kotlin\n\n```kotlin\nval asset: Asset = BitmapFactory.decodeResource(resources, R.drawable.image).let { bitmap -\u003e\n createAssetFromBitmap(bitmap)\n}\nval request: PutDataRequest = PutDataRequest.create(\"/image\").apply {\n putAsset(\"profileImage\", asset)\n}\nval putTask: Task\u003cDataItem\u003e = Wearable.getDataClient(context).putDataItem(request)\n```\n\n### Java\n\n```java\nBitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);\nAsset asset = createAssetFromBitmap(bitmap);\nPutDataRequest request = PutDataRequest.create(\"/image\");\nrequest.putAsset(\"profileImage\", asset);\nTask\u003cDataItem\u003e putTask = Wearable.getDataClient(context).putDataItem(request);\n```\n\n\u003cbr /\u003e\n\nThe following sample uses `PutDataMapRequest`: \n\n### Kotlin\n\n```kotlin\nval asset: Asset = BitmapFactory.decodeResource(resources, R.drawable.image).let { bitmap -\u003e\n createAssetFromBitmap(bitmap)\n}\nval request: PutDataRequest = PutDataMapRequest.create(\"/image\").run {\n dataMap.putAsset(\"profileImage\", asset)\n asPutDataRequest()\n}\nval putTask: Task\u003cDataItem\u003e = Wearable.getDataClient(context).putDataItem(request)\n```\n\n### Java\n\n```java\nBitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);\nAsset asset = createAssetFromBitmap(bitmap);\nPutDataMapRequest dataMap = PutDataMapRequest.create(\"/image\");\ndataMap.getDataMap().putAsset(\"profileImage\", asset);\nPutDataRequest request = dataMap.asPutDataRequest();\nTask\u003cDataItem\u003e putTask = Wearable.getDataClient(context).putDataItem(request);\n```\n\n\u003cbr /\u003e\n\n### Receive assets\n\n\nWhen an asset is created, you probably want to read and extract\nit on other side of the connection. Here's an example of how to implement the\ncallback to detect an asset change and extract the asset: \n\n### Kotlin\n\n```kotlin\noverride fun onDataChanged(dataEvents: DataEventBuffer) {\n dataEvents\n .filter { it.type == DataEvent.TYPE_CHANGED && it.dataItem.uri.path == \"/image\" }\n .forEach { event -\u003e\n val bitmap: Bitmap? = DataMapItem.fromDataItem(event.dataItem)\n .dataMap.getAsset(\"profileImage\")\n .let { asset -\u003e loadBitmapFromAsset(asset) }\n // Do something with the bitmap\n }\n}\n\nfun loadBitmapFromAsset(asset: Asset): Bitmap? {\n // Convert asset into a file descriptor and block until it's ready\n val assetInputStream: InputStream? =\n Tasks.await(Wearable.getDataClient(context).getFdForAsset(asset))\n ?.inputStream\n\n return assetInputStream?.let { inputStream -\u003e\n // Decode the stream into a bitmap\n BitmapFactory.decodeStream(inputStream)\n } ?: run {\n Log.w(TAG, \"Requested an unknown Asset.\")\n null\n }\n}\n```\n\n### Java\n\n```java\n@Override\npublic void onDataChanged(DataEventBuffer dataEvents) {\n for (DataEvent event : dataEvents) {\n if (event.getType() == DataEvent.TYPE_CHANGED &&\n event.getDataItem().getUri().getPath().equals(\"/image\")) {\n DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());\n Asset profileAsset = dataMapItem.getDataMap().getAsset(\"profileImage\");\n Bitmap bitmap = loadBitmapFromAsset(profileAsset);\n // Do something with the bitmap\n }\n }\n}\n\npublic Bitmap loadBitmapFromAsset(Asset asset) {\n if (asset == null) {\n throw new IllegalArgumentException(\"Asset must be non-null\");\n }\n // Convert asset into a file descriptor and block until it's ready\n InputStream assetInputStream =\n Tasks.await(Wearable.getDataClient(context).getFdForAsset(asset))\n .getInputStream();\n if (assetInputStream == null) {\n Log.w(TAG, \"Requested an unknown Asset.\");\n return null;\n }\n // Decode the stream into a bitmap\n return BitmapFactory.decodeStream(assetInputStream);\n}\n```\n\nFor more information, see the [DataLayer sample project](https://github.com/android/wear-os-samples/tree/main/DataLayer) on GitHub."]]