我试图实现SensorEventListener但由于某种原因没有任何事情发生。 我已经厌倦了为听众创建一个单独的类但它仍然无法正常工作。 该服务在一个单独的线程中运行。(在清单android:process =“:myproces”中)
public class Servicee extends Service {
private SensorManager sensorManager;
private long lastUpdate;
SensorEventListener listen;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
sensorManager = (SensorManager) getApplicationContext()
.getSystemService(SENSOR_SERVICE);
lastUpdate = System.currentTimeMillis();
listen = new SensorListen();
return START_STICKY;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Started", 1000).show();
super.onCreate();
}
private void getAccelerometer(SensorEvent event) {
float[] values = event.values;
// Movement
float x = values[0];
float y = values[1];
float z = values[2];
float accelationSquareRoot = (x * x + y * y + z * z)
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
long actualTime = System.currentTimeMillis();
if (accelationSquareRoot >= 7) //
{
if (actualTime - lastUpdate < 2000) {
return;
}
lastUpdate = actualTime;
Toast.makeText(this,
"Device was shuffed _ " + accelationSquareRoot,
Toast.LENGTH_SHORT).show();
Vibrator v = (Vibrator) getApplicationContext().getSystemService(VIBRATOR_SERVICE);
v.vibrate(1000);
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
sensorManager.unregisterListener(listen);
Toast.makeText(this, "Destroy", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
public class SensorListen implements SensorEventListener{
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
getAccelerometer(event);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
它可能出现什么问题?
答案 0 :(得分:5)
我认为问题,至少在提供的代码中,您从未注册接收加速计事件。
您需要使用代码来获取加速计传感器并进行注册;这应该在返回之前进入onStartCommand()。
Sensor accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(listen, accel, SensorManager.SENSOR_DELAY_NORMAL);