2

I want to get current location in background every 15 mins. I have created a background service with Timer. But it stops at some point of time.

Please correct me, how to run this all time in background without stopping?

public class BackgroundService extends Service implements LocationListener {

    public static String str_receiver = "app.BackgroundService.Locationreceiver";
    boolean isGPSEnable = false;
    boolean isNetworkEnable = false;
    double latitude, longitude;
    LocationManager locationManager;
    Location location;
    long notify_interval = 600000;
    Intent intent;
    private Handler mHandler = new Handler();
    private Timer mTimer = null;

    public BackgroundService() {

    }

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

    @Override
    public void onCreate() {
        super.onCreate();

        Toast.makeText(BackgroundService.this, "Getting Location", Toast.LENGTH_SHORT).show();

        mTimer = new Timer();
        mTimer.schedule(new TimerTaskToGetLocation(), 60000, notify_interval);
        intent = new Intent(str_receiver);
    }

    @Override
    public void onLocationChanged(Location location) {

    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    private void fn_getlocation() {
        locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
        isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnable && !isNetworkEnable) {
            Toast.makeText(BackgroundService.this, "GPS disabled", Toast.LENGTH_LONG).show();
        } else {

            if (isNetworkEnable) {
                location = null;
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000000, 20, this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {

                        Log.e("latitude", location.getLatitude() + "");
                        Log.e("longitude >>", location.getLongitude() + "");

                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        fn_update(location);
                    }
                }

            }

            if (isGPSEnable) {
                location = null;
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000000, 20, this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (location != null) {
                        Log.e("latitude>>", location.getLatitude() + "");
                        Log.e("longitude", location.getLongitude() + "");
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        fn_update(location);
                    }
                }
            }

        }
    }

    private void fn_update(Location location) {
        intent.putExtra("latutide", location.getLatitude() + "");
        intent.putExtra("longitude", location.getLongitude() + "");
        sendBroadcast(intent);
    }

    private class TimerTaskToGetLocation extends TimerTask {
        @Override
        public void run() {

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    fn_getlocation();
                }
            });

        }
    }

In Manifest

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Alexis Philip
  • 517
  • 2
  • 5
  • 23
GK_
  • 1,212
  • 1
  • 12
  • 26
  • 2
    Partial wakelock + turn off battery optimization. See https://stackoverflow.com/questions/9000563/partial-wake-lock-is-not-working, and also https://stackoverflow.com/questions/39256501/check-if-battery-optimization-is-enabled-or-not-for-an-app. –  Apr 25 '20 at 15:26

1 Answers1

1

The thing is location services are expensive for android. Thus, android os stops heavy background services when the apps go in the background. That is why you do not get the location or in some cases, you might get the Old location itself.

Please take a look at this, Background Execution Limit in android for having idea about the problem.

https://medium.com/exploring-android/exploring-background-execution-limits-on-android-oreo-ab384762a66c

So, you should use ForegroundService which generates a Notification while the service is running.

Its onCreate() is somewhat like

 override fun onCreate() {
    super.onCreate()
    log("The service has been created".toUpperCase())
    var notification = createNotification()
    startForeground(1, notification)
}

And it should be started as

context.startForegroundService(it)

Here, is an article regarding its detailed implementation. This should help you I hope.

Amit Gupta
  • 633
  • 1
  • 8
  • 19
  • Regardless, the service stopped... I've been tracking it......on an actual journey. – Maku Sep 28 '20 at 17:44