我需要从指南针获取值并在rxJava中执行。 所以我已经制作了这段代码:
private void goCompass()
{
Observable.create(new Observable.OnSubscribe<SensorEventListener>()
{
SensorEventListener listener = null;
@Override
public void call(final Subscriber<? super SensorEventListener> subscriber)
{
Sensor gsensor;
Sensor msensor;
final float[] mGravity = new float[3];
final float[] mGeomagnetic = new float[3];
listener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
final float alpha = 0.97f;
Float azimuth = 0f;
synchronized (this) {
if(switchChecked == false) {
subscriber.onNext(listener);
subscriber.onCompleted();
}
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
mGravity[0] = alpha * mGravity[0] + (1 - alpha)
* event.values[0];
mGravity[1] = alpha * mGravity[1] + (1 - alpha)
* event.values[1];
mGravity[2] = alpha * mGravity[2] + (1 - alpha)
* event.values[2];
// mGravity = event.values;
// Log.e(TAG, Float.toString(mGravity[0]));
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
// mGeomagnetic = event.values;
mGeomagnetic[0] = alpha * mGeomagnetic[0] + (1 - alpha)
* event.values[0];
mGeomagnetic[1] = alpha * mGeomagnetic[1] + (1 - alpha)
* event.values[1];
mGeomagnetic[2] = alpha * mGeomagnetic[2] + (1 - alpha)
* event.values[2];
// Log.e(TAG, Float.toString(event.values[0]));
}
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, mGravity,
mGeomagnetic);
if (success) {
float orientation[] = new float[3];
SensorManager.getOrientation(R, orientation);
azimuth = (float) Math.toDegrees(orientation[0]); // orientation
azimuth = (azimuth + 360) % 360;
Log.d("obs", "azimuth (rad): " + azimuth);
layout.setRotation(azimuth);
imageView.setRotation(-azimuth);
contlayout.setRotation(azimuth);
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
sensorManager = (SensorManager) getActivity()
.getSystemService(Context.SENSOR_SERVICE);
gsensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
msensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
sensorManager.registerListener(listener, gsensor,
SensorManager.SENSOR_DELAY_FASTEST);
sensorManager.registerListener(listener, msensor,
SensorManager.SENSOR_DELAY_FASTEST);
}
}).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<SensorEventListener>() {
@Override
public void onCompleted()
{
}
@Override
public void onError(Throwable e)
{
}
@Override
public void onNext(SensorEventListener listener)
{
sensorManager.unregisterListener(listener);
}
});
}
它有效。但是,我正处于rxJava的开头,我想知道是否有更好的方法来做这件事:
Schedulers.io()
我还需要runOnUiThread()
方法。还有其他方法吗?
感谢您的帮助