【收集表】欢迎各位来填写查看调查表
好的,以下是获取智能手表对心率以及脉搏的收集的代码,需要在智能手表开发环境中运行:
```
// 导入相关库
import android.content.Context;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.DataItem;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.Wearable;
// 在Activity中实现DataApi.DataListener接口
public class MainActivity extends WearableActivity implements DataApi.DataListener,
GoogleApiClient.ConnectionCallbacks {
private static final String TAG = "MainActivity";
private static final String HEART_RATE_PATH = "/heart_rate"; // 心率数据路径
private static final String PULSE_PATH = "/pulse"; // 脉搏数据路径
private TextView mHeartRateTextView; // 显示心率的TextView
private TextView mPulseTextView; // 显示脉搏的TextView
private GoogleApiClient mGoogleApiClient; // GoogleApiClient对象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化GoogleApiClient对象
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.build();
mHeartRateTextView = (TextView) findViewById(R.id.heart_rate);
mPulseTextView = (TextView) findViewById(R.id.pulse);
}
@Override
public void onConnected(Bundle bundle) {
Wearable.DataApi.addListener(mGoogleApiClient, this); // 添加数据监听器
}
@Override
public void onConnectionSuspended(int i) {
Wearable.DataApi.removeListener(mGoogleApiClient, this); // 移除数据监听器
}
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
for (DataEvent event : dataEvents) {
if (event.getType() == DataEvent.TYPE_CHANGED) {
DataItem dataItem = event.getDataItem();
if (dataItem.getUri().getPath().equals(HEART_RATE_PATH)) {
// 获取心率数据
DataMap dataMap = DataMapItem.fromDataItem(dataItem).getDataMap();
int heartRate = dataMap.getInt("heart_rate");
Log.d(TAG, "Heart rate: " + heartRate);
mHeartRateTextView.setText("Heart rate: " + heartRate);
} else if (dataItem.getUri().getPath().equals(PULSE_PATH)) {
// 获取脉搏数据
DataMap dataMap = DataMapItem.fromDataItem(dataItem).getDataMap();
int pulse = dataMap.getInt("pulse");
Log.d(TAG, "Pulse: " + pulse);
mPulseTextView.setText("Pulse: " + pulse);
}
}
}
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect(); // 连接GoogleApiClient
}
@Override
protected void onStop() {
mGoogleApiClient.disconnect(); // 断开GoogleApiClient
super.onStop();
}