从活动/片段内部的移动端,创建连接
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
Log.d(LOG_TAG, "API client connected");
}
@Override
public void onConnectionSuspended(int i) {
Log.d(LOG_TAG, "API client connection suspended");
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(LOG_TAG, "API client connection failed");
}
})
.addApi(Wearable.API)
.build();
mGoogleApiClient.connect();
使用 DataMap 发送数据项
PutDataMapRequest putDataMapRequest = PutDataMapRequest.create("/app");
putDataMapRequest.getDataMap().putString("DATA", data); // your data
PutDataRequest putDataRequest = putDataMapRequest.asPutDataRequest();
PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi.putDataItem(mGoogleApiClient, putDataRequest);
pendingResult.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
@Override
public void onResult(DataApi.DataItemResult dataItemResult) {
if (dataItemResult.getStatus().isSuccess()){
Log.d(LOG_TAG, "Sent weather data to watch");
}
else{
Log.d(LOG_TAG, "Unable to send data to watch");
}
mGoogleApiClient.disconnect();
}
});
依赖项
compile 'com.google.android.support:wearable:1.1.0'
compile 'com.google.android.gms:play-services-wearable:7.8.0'
从 Wear 端,接收活动中的数据
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(getBaseContext())
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
Log.d(LOG_TAG, "API client connected");
final DataApi.DataListener dataListener = new DataApi.DataListener() {
@Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
Log.e(LOG_TAG, "onDataChanged(): " + dataEventBuffer);
for (DataEvent event: dataEventBuffer){
if (event.getType() == DataEvent.TYPE_CHANGED){
DataItem dataItem = event.getDataItem();
if (dataItem.getUri().getPath().equals("/app")){
DataMap dataMap = DataMapItem.fromDataItem(dataItem).getDataMap();
String data = dataMap.getString("DATA"); // You have received the data, do your stuff
Log.d(LOG_TAG, "data " + data);
}
}
}
}
};
Wearable.DataApi.addListener(mGoogleApiClient, dataListener);
}
@Override
public void onConnectionSuspended(int i) {
Log.d(LOG_TAG, "API client connection suspended");
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.d(LOG_TAG, "API client connection failed");
}
})
.addApi(Wearable.API)
.build();
mGoogleApiClient.connect();
依赖项
compile 'com.google.android.support:wearable:1.3.0'
compile 'com.google.android.gms:play-services-wearable:7.8.0'