您如何在Android应用和穿戴OS应用之间同步数据?

时间:2019-02-08 05:08:18

标签: android android-studio wear-os wearables

我有两个要共享信息的应用程序,一个用于Android智能手机,另一个用于磨损OS设备(例如smartwatch)。我想将信息从智能手表发送到手机。我关注了api文档(https://developer.android.com/training/wearables/data-layer/data-items),并将其用于电话应用程序:

@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    for (DataEvent event : dataEvents) {
        if(event.getType() == DataEvent.TYPE_CHANGED) {
            // DataItem changed
            DataItem item = event.getDataItem();
            if (item.getUri().getPath().compareTo("/sensor_data") == 0) {
                DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
                String sensors = "";
                sensors += dataMap.getDouble(HEART_BEAT_KEY);
                sensors += dataMap.getDouble(ACCELEROMETER_X_KEY);
                sensors += dataMap.getDouble(ACCELEROMETER_Y_KEY);
                sensors += dataMap.getDouble(ACCELEROMETER_Z_KEY);
                sensors += dataMap.getDouble(GYROSCOPE_X_KEY);
                sensors += dataMap.getDouble(GYROSCOPE_Y_KEY);
                sensors += dataMap.getDouble(GYROSCOPE_Z_KEY);
                sensors += dataMap.getDouble(AMBIENT_LIGHT_KEY);
                mTextView.setText(sensors);
            }
        }
    }
}

以及onCreateView函数中的内容(此内容在一个片段中):

Wearable.getDataClient(this.getContext()).addListener(this);

wear os应用程序仅在onCreate函数中具有以下功能:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mDataClient = Wearable.getDataClient(this.getApplicationContext());

    // Code from Android Tutorial: https://developer.android.com/training/wearables/data-layer/data-items
    PutDataMapRequest putDataMapReq = PutDataMapRequest.create("/sensor_data");
    putDataMapReq.getDataMap().putDouble(HEART_BEAT_KEY, mHeartBeat);
    putDataMapReq.getDataMap().putDouble(ACCELEROMETER_X_KEY, mAccelerometerX);
    putDataMapReq.getDataMap().putDouble(ACCELEROMETER_Y_KEY, mAccelerometerY);
    putDataMapReq.getDataMap().putDouble(ACCELEROMETER_Z_KEY, mAccelerometerZ);
    putDataMapReq.getDataMap().putDouble(GYROSCOPE_X_KEY, mGyroscopeX);
    putDataMapReq.getDataMap().putDouble(GYROSCOPE_Y_KEY, mGyroscopeY);
    putDataMapReq.getDataMap().putDouble(GYROSCOPE_Z_KEY, mGyroscopeZ);
    putDataMapReq.getDataMap().putDouble(AMBIENT_LIGHT_KEY, mAmbientLight);
    PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();
    putDataReq.setUrgent();
    Task<DataItem> putDataTask = mDataClient.putDataItem(putDataReq);

    // Enables Always-on
    setAmbientEnabled();
}

问题在于电话应用程序中从未调用过onDataChanged函数。我尝试过将onDataChanged函数移到fragment活动上,以使其与api文档更加匹配,但这也不起作用。关于我可能做错了什么建议?

0 个答案:

没有答案