0
我目前正在實施滾動型因此我想包括的ImageView通過一個 RotationVectorSensor滾動和 SensorEventListener。
Android的 - 獲取MotionSensor失敗(空指針)
這是我到目前爲止的代碼:
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.widget.HorizontalScrollView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor sensor;
private HorizontalScrollView scrollView;
private String TAG = MainActivity.class.getSimpleName();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
if (sensor != null) {
sensorManager.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
Log.d(TAG, "Sensor found.");
} else {
Log.e(TAG, "Sensor NOT found.");
Toast.makeText(this, "ROTATION_VECTOR Sensor not found",
Toast.LENGTH_LONG).show();
finish();
}
scrollView = (HorizontalScrollView) findViewById(R.id.panoramaScrollView);
Log.d(TAG, "Panorama Scroll View found.");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
Toast.makeText(this, "rotating Yippi!", Toast.LENGTH_LONG).show();
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
final float angle = event.values[2];
scrollView.post(new Runnable() {
public void run() {
if (scrollView != null) {
scrollView.scrollTo((int)angle, scrollView.getBottom());
Log.d(TAG, "scrollTo executed.");
}
}
});
}
}
@Override
public void onResume() {
super.onResume();
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
Log.d(TAG, "SensorListener registered");
}
@Override
public void onPause() {
super.onPause();
if (sensor != null) {
sensorManager.unregisterListener(this);
Log.d(TAG, "SensorListener unregistered");
}
}
}
傳感器初始化後直接空指針發生:
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
爲此應用程序退出,並打印:「傳感器未找到」 ..
有什麼我忘記了嗎?
在此先感謝!
您是否檢查過您的設備是否具有該特定傳感器?它看起來好像沒有。 –
我還沒有想過,但是RotationSensor不僅僅是MagneticFieldSensor和Accelerometer的組合嗎? –
清單中是否可能缺少特定權限? –