我目前正在尝试实现一个 ScrollView ,我希望包含的 ImageView 滚动到 RotationVectorSensor 和 SensorEventListener 。
到目前为止,这是我的代码:
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");
}
}
}
Nullpointer在传感器初始化后直接出现:
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
因此,应用退出并打印:“未找到传感器”......
有什么我忘记了吗? 提前谢谢!
答案 0 :(得分:0)
我找到了解决方案。 android清单中缺少以下几行:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>