Search code examples
javaandroidlocationlistenerbackground-serviceandroid-gps

LocationListener doesn't provide update after sometime in android service


I am writing an application where I need to get the location updates really fast from background. Hence, I've written a service to achieve the required outcome.

I am starting the service from an activity's onCreate() method.

The problem I am facing is, the service is able to provide location update for about 20 to 30 seconds from the time of activation of service. Then I am not getting any updates.

Here is the code for the service:

public class MyLocService extends Service
        implements
        LocationListener{

  private final LocationListener locationListener = this;

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Handler handler = new Handler(Looper.getMainLooper());
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (checkPermission()) {
                    manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

                    manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
                    manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
                }
                else{
                    //Request Permission
                    Intent permissionIntent = new Intent();
                    permissionIntent.setAction(LOCATION_PERMISSION_REQUIRED);
                    sendBroadcast(permissionIntent);
                }
                Looper.loop();
            }
        };

        handler.post(runnable);

        //Create notification nad run in foreground
        startForeground(
                NotificationCreator.getNotificationId(),
                NotificationCreator.getNotification(context)
        );

        return Service.START_STICKY;

}

@Override
public void onLocationChanged(Location location) {
     Log.d("LocUpdate",  location.getLatitude() + " : " + location.getLongitude());
}

Every time I start the service from the activity like :

Intent intent = new Intent(this, MyLocService.class);
startService(intent);

I get updates in the onLocationChange() for 20 to 30 seconds.

Another observation is : if I keep the activity (from where I am starting the service open and visible) then I continue to get the location updates. However when I close the activity or kill the app and allow the service (alone) to run in the background, I am not getting any location updates although the service is running as I can see the notification at the top of my screen.

What am I doing wrong?


Solution

  • I've solved the problem. Turn off the battery optimization in miui or add the app as exception. Code works perfectly.