我最近开始在 Android 设备上工作,我想从 Android Watch 收集传感器数据。
我成功使用了 Message API,但 Data API 对我不起作用。我检查过:
https://stackoverflow.com/a/34175410/2487227
未调用 Android Wear onDataChanged
但他们都没有为我工作。
我的手表代码:
@Override
public void onCreate() {
super.onCreate();
// sensor registration
// ......
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
googleApiClient.connect();
Log.i(this.getClass().toString(), "Google API Client connected");
}
private void sendSensorResult(SensorEvent event) {
if (!googleApiClient.isConnected())
googleApiClient.connect();
PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(DATA_API_PATH);
putDataMapRequest.getDataMap().putLong("UNIX_TIME", System.currentTimeMillis());
putDataMapRequest.getDataMap().putInt("TYPE", event.sensor.getType());
// nanosecond
putDataMapRequest.getDataMap().putLong("TIME", event.timestamp);
putDataMapRequest.getDataMap().putFloatArray("DATA", event.values);
PutDataRequest request = putDataMapRequest.asPutDataRequest().setUrgent();
Wearable.DataApi.putDataItem(googleApiClient, request)
.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
@Override
public void onResult(@NonNull DataApi.DataItemResult dataItemResult) {
if (dataItemResult.getStatus().isSuccess()) {
Log.i(this.getClass().toString(), "Sent: " + event.toString());
} else {
Log.i(this.getClass().toString(), "FAILED TO SEND: " + event.toString());
}
}
});
}
在电话上:
public void onDataChanged(DataEventBuffer dataEvents) {
Log.i(this.getClass().toString(), "Got data at " + System.currentTimeMillis());
for (DataEvent dataEvent : dataEvents) {
Log.i(this.getClass().toString(), "Got event: " + dataEvent.toString());
if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
DataMap dataMap = DataMapItem.fromDataItem(dataEvent.getDataItem()).getDataMap();
String path = dataEvent.getDataItem().getUri().getPath();
if (path.equals(DATA_API_PATH)) {
int type = dataMap.getInt("TYPE");
long time = dataMap.getLong("TIME");
float[] data = dataMap.getFloatArray("DATA");
String message = String.format(Locale.UK, "TYPE: %d, TIME: %d, DATA: %s",
type,
time,
Arrays.toString(data));
showSensorResult(message);
}
}
}
}
电话AndroidManifest.xml
:
<service
android:name=".WearableSensorListener"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.android.gms.wearable.DATA_CHANGED"/>
<data android:host="*"
android:scheme="wear"
android:pathPrefix="/wearable-sensor"/>
</intent-filter>
</service>
我可以从手表上看到日志,但手机上没有任何显示。
可穿戴设备和手机的applicationId
s是一样的。
我是否需要任何额外的权限才能使用 Data API?