我试图每隔5秒将磁场传感器的数据发送到服务器,但是我面临的问题是取消注册sensorListerner读取数据。我已经尝试过这样的sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),1000 * 10);
,但没有经过考验。目前,数据将在一秒钟内发送到服务器12次。
我感谢任何帮助。
代码:
public class MainActivity extends ActionBarActivity implements
SensorEventListener {
String telsaString;
private TextView magneticX;
private TextView magneticY;
private TextView magneticZ;
private TextView magneticT;
private SensorManager sensorManager = null;
private float magX;
private float magY;
private float magZ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
// Capture magnetic sensor related view elements
magneticX = (TextView) findViewById(R.id.valMag_X);
magneticY = (TextView) findViewById(R.id.valMag_Y);
magneticZ = (TextView) findViewById(R.id.valMag_Z);
magneticT = (TextView) findViewById(R.id.valMag_T);
// Register magnetic sensor
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_NORMAL);
final SensorEventListener listener = this;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
sensorManager.unregisterListener(listener);
}
}, 5000);
}
@Override
protected void onPause() {
// Unregister the listener
sensorManager.unregisterListener(this);
super.onPause();
}
@Override
protected void onStop() {
// Unregister the listener
sensorManager.unregisterListener(this);
super.onStop();
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_NORMAL);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent sensorEvent) {
synchronized (this) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
magX = sensorEvent.values[0];
magY = sensorEvent.values[1];
magZ = sensorEvent.values[2];
magneticX.setText(Float.toString(sensorEvent.values[0]));
magneticY.setText(Float.toString(sensorEvent.values[1]));
magneticZ.setText(Float.toString(sensorEvent.values[2]));
double teslaXYZ = (Math.sqrt((magX * magX) + (magY * magY)
+ (magZ * magZ)));
magneticT.setText(Double.toString(teslaXYZ));
try {
JSONObject tesla = new JSONObject();
tesla.put("tesla", teslaXYZ);
telsaString = tesla.toString();
new MyAsyncTask().execute(telsaString);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
修改
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
10*1000*1000);
.
.
.
.
long curTime = System.currentTimeMillis();
if ((curTime - lastUpdate) > 10000) {
lastUpdate = curTime;
}
答案 0 :(得分:1)
您提供的费率1000 * 10
以微秒为单位,因此您要求的是10毫秒更新周期。请注意,请求的采样周期仅是请求。 费率可能更快或更慢,您需要跟踪时间并做适当的事情。如果您希望完全停止接收事件,请使用SensorManager.unregisterListener()
方法取消注册您的听众。