如何将使用SensorListener的程序转换为SensorEventListener
||
我正在创建一个名为CompassApp的应用程序。我创建了两个名为Compass.java和Rose.java的类。该应用程序是根据网站中描述的教程创建的,并且使用了不建议使用的SensorListener版本。 Compass.java类正在使用此不建议使用的版本。使用不推荐使用的版本时,该应用程序运行良好。然后,我想将我的应用程序转换为SensorEventListener的当前版本。但是指南针的旋转停止了!我被困住了,不知道该怎么办。请帮我。
具有不推荐使用的SensorListener接口的Compass.java
public class Compass extends Activity implements SensorListener {
SensorManager sensorManager;
static final int sensor = SensorManager.SENSOR_ORIENTATION;
MyRose rose;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set full screen view
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
rose = new MyRose(this);
setContentView(rose);
// get sensor manager
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
}
// register to listen to sensors
@Override
public void onResume() {
super.onResume();
sensorManager.registerListener(this, sensor);
}
// unregister
@Override
public void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
// Ignore for now
public void onAccuracyChanged(int sensor, int accuracy) {
}
// Listen to sensor and provide output
public void onSensorChanged(int sensor, float[] values) {
if (sensor != Compass.sensor)
return;
int orientation = (int) values[0];
rose.setDirection(orientation);
}
}
带有新SensorEventListener的Compass.java
public class Compass extends Activity{
SensorManager sensorManager;
SensorEventListener listener ;
static final int sensor = SensorManager.SENSOR_ORIENTATION;
Rose rose;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set full screen view
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
listener = new SensorEventListener()
{
@Override
public void onSensorChanged(SensorEvent e)
{
int orientation = (int) e.values[0];
rose.setDirection(orientation);
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
};
setContentView(rose);
// get sensor manager
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(listener, sensorManager.getDefaultSensor(sensor),SensorManager.SENSOR_MAGNETIC_FIELD);
}
// register to listen to sensors
@Override
public void onResume() {
super.onResume();
sensorManager.registerListener(listener, sensorManager.getDefaultSensor(sensor), SensorManager.SENSOR_MAGNETIC_FIELD);
}
// unregister
@Override
public void onPause() {
super.onPause();
sensorManager.unregisterListener(listener);
}
}
没有找到相关结果
已邀请:
1 个回复
爆刺疤灯
编辑:添加检查以确定传感器类型