0

is service will stop working when we clear the app from recent apps? because when iam running below code. To update lat,lng when location changed.when i clear the app from recent apps the location update is getting stopped.when i see my running apps view the service was in running state.please clear the doubt how service will work exactly.Thank in Advance.

  public class GPSTracker extends Service implements
    ConnectionCallbacks,
    OnConnectionFailedListener,
    LocationListener, GooglePlayServicesClient.ConnectionCallbacks {

public static final long UPDATE_INTERVAL = 5000;
public static final long FASTEST_INTERVAL = 1000;

private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
private boolean mInProgress;
private boolean servicesAvailable = false;
DatabaseHandler db;
@Override
public void onCreate() {
    super.onCreate();

    mInProgress = false;
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)

       .setInterval(UPDATE_INTERVAL) // Set the update interval to 5 seconds
      .setFastestInterval(FASTEST_INTERVAL); // Set the fastest update interval to 1 second

    servicesAvailable = servicesConnected();
    setUpLocationClientIfNeeded();
     db = new DatabaseHandler(this);
}

private boolean servicesConnected() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    return ConnectionResult.SUCCESS == resultCode;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    Log.d("TAG", "onLocationChanged onStart Command");
    if (!servicesAvailable || mLocationClient.isConnected() || mInProgress)
        return START_STICKY;

    setUpLocationClientIfNeeded();

    if (!mLocationClient.isConnected() || !mLocationClient.isConnecting() && !mInProgress) {
        mInProgress = true;
        mLocationClient.connect();
    }

    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

  @Override
   public void onDestroy() {
 /*   mInProgress = false;
    if (servicesAvailable && mLocationClient != null) {
        mLocationClient.removeLocationUpdates( this);
        mLocationClient = null;
    }
   */
    super.onDestroy();
}

private void setUpLocationClientIfNeeded() {
    if (mLocationClient == null)
        mLocationClient = new LocationClient(this, this, this);
}

/*
 * LocationListener Callbacks
 */

@Override
public void onLocationChanged(Location location) {
    //Carnival.updateLocation(location);
    Log.d("TAG", "onLocationChanged " + location.getLongitude());
    Log.d("Insert: ", "Inserting ..");
    db.addContact(new Contact("" + location.getTime(), " Latitude " + location.getLatitude() + " Longitude " + location.getLongitude()));

}



/*
* GooglePlayServicesClient Callbacks
*/

@Override
public void onConnected(Bundle bundle) {
    if (mLocationClient != null) {
        mLocationClient.requestLocationUpdates(mLocationRequest, this);
    }
}

@Override
public void onDisconnected() {

}

@Override
public void onConnectionSuspended(int i) {

}



@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    mInProgress = false;
    /*
    * Google Play services can resolve some errors it detects.
    * If the error has a resolution, try sending an Intent to
    * start a Google Play services activity that can resolve
    * error.
    */
    if (!connectionResult.hasResolution()) {
        // If no resolution is available, display an error dialog
    }
}
}
Sandeep Kumar
  • 350
  • 4
  • 18

3 Answers3

1

A regular Service won't be enough to ensure that the system isn't going to kill it while he/she clears our app from the Recent list.

For that particular purpose, tell the system that you want the Service to be run as a foreground:

A foreground service is a service that's considered to be something the user is actively aware of and thus not a candidate for the system to kill…

You do that by calling this from within a Service:

    Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text), System.currentTimeMillis());
    Intent notificationIntent = new Intent(this, ExampleActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);

    startForeground(ONGOING_NOTIFICATION_ID, notification);

As you can see, startForeground() takes in a Notification as one of its parameters. For eventually it will put a persistent notification to inform the users that your Service is currently running in the background.


After doing a couple more research on this, it seems like making a Service foreground isn't quite enough to ensure its persistence on conditions like this.

One workaround is then to listen when our app is being swiped away from Recents list and explicitly restart our Service from there by doing so:

    @Override 
    public void onTaskRemoved(Intent rootIntent){
         Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());

         PendingIntent restartServicePendingIntent = PendingIntent.getService(
         getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
         AlarmManager alarmService = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
         alarmService.set(ELAPSED_REALTIME, elapsedRealtime() + 1000, restartServicePendingIntent);

         super.onTaskRemoved(rootIntent); 
    }

Of course, you have to add the appropriate flag on the Service's declaration on the Manifest (see Max Rockwood's answer).

Community
  • 1
  • 1
Hadi Satrio
  • 428
  • 2
  • 8
0

you need to set stopWithTask=false in manifest for service.

Something like this:

<service
    android:enabled="true"
    android:name=".MyService"
    android:stopWithTask="false" />

It prevents the service from stopping and there is method onTaskRemoved() which gets called if we clear the app from recents if you want to perform any action you can ovorride it.it.

Atiq
  • 14,435
  • 6
  • 54
  • 69
0

There is an event named OnStartCommand(). Override it and call the activity again in that function.

double-beep
  • 5,031
  • 17
  • 33
  • 41