Have you looked at the samples for API 20? There is a good demonstration of using DataApi in the DataLayer sample located here:
{android-sdk-root}\samples\android-20\wearable\DataLayer
I also posted an example of using DataApi in my answer for Android Wear Watchface Settings on the host
But probably due to the name of this question there is no simple relationship with DataApi . So maybe this is a good place to post it again - hope more users find this example. See code below:
All pressed DataApi buttons DataApi shared between devices and available for both of them. You can change this data on both sides, and the other side will be immediately notified of this change (when the devices are connected to each other). You can also read stored data at any time. Here is sample code for implementing DataApi in a few simple steps.
On the phone side:
public class WatchfaceConfigActivity extends Activity { private GoogleApiClient mGoogleApiClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(new ConnectionCallbacks() { @Override public void onConnected(Bundle connectionHint) { } @Override public void onConnectionSuspended(int cause) { } }) .addOnConnectionFailedListener(new OnConnectionFailedListener() { @Override public void onConnectionFailed(ConnectionResult result) { } }) .addApi(Wearable.API) .build(); mGoogleApiClient.connect(); }
and every time you want to sync a new configuration with an Android Wear device, you have to put a DataRequest through Wearable DataApi :
private void syncSampleDataItem() { if(mGoogleApiClient==null) return; final PutDataMapRequest putRequest = PutDataMapRequest.create("/SAMPLE"); final DataMap map = putRequest.getDataMap(); map.putInt("color", Color.RED); map.putString("string_example", "Sample String"); Wearable.DataApi.putDataItem(mGoogleApiClient, putRequest.asPutDataRequest()); } }
On the guard side:
You need to create a class that extends WearableListenerService :
public class DataLayerListenerService extends WearableListenerService { @Override public void onDataChanged(DataEventBuffer dataEvents) { super.onDataChanged(dataEvents); final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents); for(DataEvent event : events) { final Uri uri = event.getDataItem().getUri(); final String path = uri!=null ? uri.getPath() : null; if("/SAMPLE".equals(path)) { final DataMap map = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
and declare it in your AndroidManifest :
<service android:name=".DataLayerListenerService" > <intent-filter> <action android:name="com.google.android.gms.wearable.BIND_LISTENER" /> </intent-filter> </service>
source share