I want to do something like this:
When my application starts I want to start a Service which should check my location
When the application goes to background I want to stop the service
I have two major problems:
How can I detect that my application goes to background? I haver several activities, and I tried that in my MainActivity overriding onPause, but the onPause is also called when I start an other activity.
This problem is more important: How should my Service which checks for my location look like? I tried several approaches, but no success.
My Service looks like this, and it's not working. What should I change to make it work?
package com.pivoscore.service;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
public class LocationService extends Service {
private LocationListener locationListener;
@Override
public IBinder onBind(final Intent intent) {
return null;
}
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
super.onStartCommand(intent, flags, startId);
return Service.START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
final LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
this.locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100, 0, this.locationListener);
}
private static class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(final Location location) {
}
@Override
public void onProviderDisabled(final String provider) {
}
@Override
public void onProviderEnabled(final String provider) {
}
@Override
public void onStatusChanged(final String provider, final int status, final Bundle extras) {
}
}
}