Search code examples
javaandroid-studioandroid-intentbackground-process

Run an IntentService without an Activity


I have a service which needs to run permanently in the background, but as soon as the activity closes so does the IntentService created by it:

public class CAS extends IntentService {
  public CAS() {
    super("CAS");
  }

  Sensor accelerometer;
  SensorManager sensorManager;
  CA cA= new CA();

  @Override
  protected void onHandleIntent(@Nullable Intent intent) {
    sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);

    accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

    sensorManager.registerListener(cA, accelerometer, SensorManager.SENSOR_DELAY_FASTEST);

    LocationManager locationManager = GlobalFunctions.LocationLibrary.getLocationManager(this);

    cA.start(this, locationManager);
  }
}

How can I go about making this class run indefinitely in the background, even starting up when Android does?


Solution

  • You need to register the service with a BroadcastReceiver

    Here is a sample program on the same.

    Check this answer for restarting the service when device is rebooted

    Documentation of BroadcastReceiver