如何在android中运行后台服务以使用加速度计?
我已经拥有一个侦听器来检测加速度计值。但我想将其添加到后台服务中。因此,即使应用程序被杀,我也会获得价值。
请让我知道解决方案吗?
任何例子都非常感谢!!!
答案 0 :(得分:3)
嗨,这是我的源代码检查出来
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
int count = 1;
private boolean init;
private Sensor mySensor;
private SensorManager SM;
private float x1, x2, x3;
private static final float ERROR = (float) 7.0;
private static final float SHAKE_THRESHOLD = 15.00f; // m/S**2
private static final int MIN_TIME_BETWEEN_SHAKES_MILLISECS = 1000;
private long mLastShakeTime;
private TextView counter;
@Override
public void onCreate() {
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
if ((curTime - mLastShakeTime) > MIN_TIME_BETWEEN_SHAKES_MILLISECS) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
double acceleration = Math.sqrt(Math.pow(x, 2) +
Math.pow(y, 2) +
Math.pow(z, 2)) - SensorManager.GRAVITY_EARTH;
Log.d("mySensor", "Acceleration is " + acceleration + "m/s^2");
if (acceleration > SHAKE_THRESHOLD) {
mLastShakeTime = curTime;
Toast.makeText(getApplicationContext(), "FALL DETECTED",
Toast.LENGTH_LONG).show();
}
}
}
}
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Start Detecting", Toast.LENGTH_LONG).show();
SM = (SensorManager) getSystemService(SENSOR_SERVICE);
mySensor = SM.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
SM.registerListener(this, mySensor, SensorManager.SENSOR_DELAY_NORMAL);
//here u should make your service foreground so it will keep working even if app closed
return Service.START_STICKY;
}
答案 1 :(得分:0)
您已使用侦听器接收加速度计值。因此,只需创建一个实现Service的SensorEventListener并按照您已经完成的方式注册此监听器。
但是关于在应用程序被杀之后保持服务运行,我认为你应该将你的服务运行到另一个进程中,在你的AndroidManifest.xml中插入这样的东西:
<service android:name=".YourService"
android:process=":accel_monitor>
</service>