java – 服务中的SensorEventListener

前端之家收集整理的这篇文章主要介绍了java – 服务中的SensorEventListener前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图实现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

    }

}

什么可能是错的?

解决方法

我相信问题,至少在提供的代码中,您从未注册接收加速度计事件.

您需要代码才能获得加速计传感器并进行注册;这应该在返回之前进入onStartCommand().

Sensor accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(listen,accel,SensorManager.SENSOR_DELAY_NORMAL);

猜你在找的Java相关文章