Search code examples
androidandroid-activityserviceandroid-manifestbackground-process

How to stop a service started after app is closed - android


I created a app with google maps to check my location and alert me if I is close to a mark.

If i close this app, i created a service to start in OnDestroy() method from my main activity. The service is started and executed very well. But when i open the app again, i need to stop this service, so i put the stopservice(intent) in OnCreate method. But the service doesn't stop and keeps sending me notification.

My Service:

public class ServiceClass extends Service{
private ArrayList<Prod> est = new ArrayList<Prod>();
private int i = 0;
private float[] distance = new float[2];

private LocationListener locationListener = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        i = 0;
        while (i < est.size()){
            Location.distanceBetween(location.getLatitude(), location.getLongitude(), est.get(i).getLocation().latitude, est.get(i).getLocation().longitude, distance);
            if (distance[0] > est.get(i).getRange()) {

            } else {
                Toast.makeText(ServiceClass.this, "in circle"+i, Toast.LENGTH_SHORT).show();

                NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(ServiceClass.this)
                                .setSmallIcon(R.mipmap.ic_launcher)
                                .setContentTitle("Distance")
                                .setContentText("Test notification");
                NotificationManager mNotificationManager =
                        (NotificationManager) getSystemService(
                                Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify(1, mBuilder.build());

                Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                r.play();
            }
            i++;
        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }
};

public ServiceClass() {
}


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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    GetLocation get = new GetLocation();
    get.execute();
    Toast.makeText(ServiceClass.this, "Service started", Toast.LENGTH_SHORT).show();
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    locationManager.removeUpdates(locationListener);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    return START_STICKY;
}

In My MapsActivity I started the service in my onDestroy:

@Override
public void onDestroy() {
    super.onDestroy();
    Intent intent = new Intent(this, ServiceClass.class);
    startService(intent);
}

It's work. the App is closed and the service started and show a notification if my location is close.


The problem is, when i open the app again i need to cancel the service to don't show notification if the app is open.

But don't worked.

I call the stopService in my onCreate:

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    Intent intent = new Intent(this, ServiceClass.class);
    stopService(intent);
}

Don't worked, the service keep sending me notification.

My service declared in manifest:

<service
     android:name=".Controller.ServiceClass"
     android:enabled="true"
     android:exported="false" >
</service>

Solution

  • You could try to override the Service's onDestroy()Method and remove the location listener from the LocationManager. You should also cancel the notification there.

    Add the following code to your Service:

    @Override
    public void onDestroy() {
       LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
       locationManager.removeUpdates(locationListener);
    
       NotificationManager mNotificationManager =
                        (NotificationManager) getSystemService(
                                Context.NOTIFICATION_SERVICE);
       mNotificationManager.cancel(1);
    }