Reputation: 15
How to run a background service in android to use accelerometer?
I am already holding a listener to detect the accelerometer values. But i want to add this to a background service. So that even the app killed then i will get the values.
Please let me know the solution for this?
Any example is highly appreciated!!!
Upvotes: 0
Views: 5234
Reputation: 315
Beginning in Android 9, only foreground services are allowed to do this according to https://developer.android.com/guide/topics/sensors/sensors_overview. This is probably because accelerometers can be used to determine how location has changed, and background location is a special opt-in permission.
Upvotes: 0
Reputation: 682
hi here is my source code check this out
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;
}
Upvotes: 4
Reputation: 546
You are already using a listener to receive the accelerometer values. So, just create a Service which implements SensorEventListener and register this listener as you already have done.
But about keep the service running even after the app is killed, I think you should run your Service into another process, insert something like this into your AndroidManifest.xml:
<service android:name=".YourService"
android:process=":accel_monitor>
</service>
Upvotes: 0