我试图从android Wear发送一些信息到智能手机,但我有两个麻烦,首先我使用PutDataRequest但它不起作用,我不知道我做错了什么:
public class MainActivity extends WearableActivity implements SensorEventListener, DataApi.DataListener, MessageApi.MessageListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setAmbientEnabled();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
apiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)//nos notifica cuando estamos conectados
.addOnConnectionFailedListener(this)// ofrece el resultado del error
.build();
if(!apiClient.isConnected())
apiClient.connect();
x = (TextView) findViewById(R.id.x);
y = (TextView) findViewById(R.id.y);
z = (TextView) findViewById(R.id.z);
}
我正在以这种方式将值发送到手机,我知道这是错误的,那么如何在一条消息中发送三个值而不是发送三条消息呢?
public void onSensorChanged(SensorEvent event) {
accelerometer[0]=event.values[0];
accelerometer[1]=event.values[1];
accelerometer[2]=event.values[2];
x.setText(Float.toString(event.values[0]));
y.setText(Float.toString(event.values[1]));
z.setText(Float.toString(event.values[2]));
//Send X acceleration
putDataMapReq = PutDataMapRequest.create(ITEM_0);
putDataMapReq.getDataMap().putFloat(KEY, accelerometer[0]);
putDataReq = putDataMapReq.asPutDataRequest();
resultado = Wearable.DataApi.putDataItem(apiClient, putDataReq);
Wearable.DataApi.putDataItem(apiClient,putDataReq);
另一方面,我通过电话收到了这些信息:
public class MainActivity extends AppCompatActivity implements DataApi.DataListener, MessageApi.MessageListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
//On create
apiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if(!apiClient.isConnected())
apiClient.connect();
在此处接收消息:
@Override
public void onDataChanged(DataEventBuffer eventos) {
for (DataEvent event : eventos) {
if (event.getType() == DataEvent.TYPE_CHANGED){
DataItem item =event.getDataItem();
if (item.getUri().getPath().equals(ITEM_0)) {
DataMapItem dataMapItem = DataMapItem.fromDataItem(item);
acel_x = dataMapItem.getDataMap().getFloat(KEY);
runOnUiThread(new Runnable() {
@Override
public void run() {
((TextView) findViewById(R.id.x)).setText(Float.toString(acel_x));
}
});
}
所以我想问你们,我应该如何发送/接收消息以及如何发送消息以避免内存溢出?
答案 0 :(得分:0)
DataMap有putFloatArray / getFloatArray。
磨损:
putDataMapReq.getDataMap().putFloatArray(KEY, accelerometer);
电话:
acel_xyz = dataMapItem.getDataMap().getFloatArray(KEY);