Pregunta

i am trying to get location updates in the background when my app gets closed. Im trying this through a service. It is working fine when my app is open, but when i close it also the service seems to get closed.

thats the code im using:

MainActivity:

public class MainActivity extends Activity {

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

MyService:

public class MyService extends Service {

public static final String BROADCAST_ACTION = "Hello World";
private static final int TWO_MINUTES = 1000 * 60 * 2;
public LocationManager locationManager;
public MyLocationListener listener;
public Location previousBestLocation = null;
private String provider;


@Override
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);      
}

@Override
public void onStart(Intent intent, int startId) {      
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
listener = new MyLocationListener();    
provider = locationManager.getBestProvider(new Criteria(), false);
locationManager.requestLocationUpdates(provider, 0, 0, listener);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);       
return START_STICKY;
}

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

protected boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
    // A new location is always better than no location
    return true;
}

// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;

// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
    return true;
// If the new location is more than two minutes older, it must be worse
} else if (isSignificantlyOlder) {
    return false;
}

// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;

// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
        currentBestLocation.getProvider());

// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
    return true;
} else if (isNewer && !isLessAccurate) {
    return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
    return true;
}
return false;
}


@Override
public void onDestroy() {       
// handler.removeCallbacks(sendUpdatesToUI);     
super.onDestroy();
Log.v("STOP_SERVICE", "DONE");
locationManager.removeUpdates(listener);        
}   

public static Thread performOnBackgroundThread(final Runnable runnable) {
final Thread t = new Thread() {
    @Override
    public void run() {
        try {
            runnable.run();
        } finally {

        }
    }
};
t.start();
return t;
}


public class MyLocationListener implements LocationListener
{

public void onLocationChanged(final Location loc)
{
    Log.i("MyService", "Location changed");
    // do something  

    }                               
}

public void onProviderDisabled(String provider)
{
}


public void onProviderEnabled(String provider)
{
 }


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

}
}
}
¿Fue útil?

Solución

Try implementing foreground service. foreground service

Foreground service displays notification and is never stopped until you want.

Implement this code snippet in your 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);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top