Getting updated latitude longitude in background without internet on android

31 views Asked by At

I want to build location tracking android app that can save coordinates of user every minute in background, our app works fine on devices with offline google maps but on devices where we don't have offline maps nor internet connection then it stop receiving location updates after some time.

trying to access Lat/long with 2 approaches Google Fused API and LocationManager using GPS_Provider both has same problem, below is my code;

public class BackgroundLocationService extends Service {

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

    }


    //Location Callback
    private LocationCallback locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);

            Location currentLocation = locationResult.getLastLocation();
            lat= Double.toString(currentLocation.getLatitude());
            longit=Double.toString(currentLocation.getLongitude());

        }
    };


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


        prepareForegroundNotification("");
        startLocationUpdates();

        return START_STICKY;
    }

    @SuppressLint("MissingPermission")
    private void startLocationUpdates() {
        mFusedLocationClient.requestLocationUpdates(this.locationRequest,
                this.locationCallback, Looper.myLooper());
    }

    private void prepareForegroundNotification(String msg) {

        if(msg.length()==0)
        {
            msg="HCM Location Tracking";
        }
        else {
            msg="HCM, "+msg;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    "1",
                    msg,
                    NotificationManager.IMPORTANCE_HIGH
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(serviceChannel);
        }
        Intent notificationIntent = new Intent(this, SplashActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                121,
                notificationIntent, PendingIntent.FLAG_IMMUTABLE);

        Notification notification = new NotificationCompat.Builder(this, "1")
                .setContentTitle(getString(R.string.app_name))
                .setContentTitle(msg)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentIntent(pendingIntent)
                .build();
        startForeground(1, notification);
    }

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

    private void initData() {

         locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, UPDATE_INTERVAL_IN_MILLISECONDS)
                .setWaitForAccurateLocation(false)
                .setMinUpdateIntervalMillis(UPDATE_INTERVAL_IN_MILLISECONDS) 
                .setMaxUpdateDelayMillis(UPDATE_INTERVAL_IN_MILLISECONDS)
                .build();

         mFusedLocationClient =
                LocationServices.getFusedLocationProviderClient(Global.getInstance());

          gpsTracker = new GPSTracker( this);
          getCoordinatesFromMangerHandler();

 

        locationSettings();

    }

    private void getCoordinatesFromMangerHandler() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getCoordinatesFromManger();
                mHandler.postDelayed(this, CHECK_INTERVAL);
            }
        }, CHECK_INTERVAL);
    }

 
     private void getCoordinatesFromManger() {
 
        if(gpsTracker==null){
            gpsTracker = new GPSTracker( this);
        }
        gpsTracker.getLocation();

        lat= Double.toString(gpsTracker.getLatitude());
        longit=Double.toString(gpsTracker.getLongitude());

 
    }

    private void locationSettings() {

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);

        SettingsClient client = LocationServices.getSettingsClient(this);
        Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
        task.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
            @Override
            public void onSuccess(LocationSettingsResponse locationSettingsResponse) {

            }
        });

        task.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                if (e instanceof ResolvableApiException) {
                      try {
                        ResolvableApiException resolvable = (ResolvableApiException) e;
                     prepareForegroundNotification("Kindly enable Wi-Fi scanning and location.");

                    } catch (Exception sendEx) {
                    }
                }
            }
        });

    }



    @Override
    public void onDestroy() {
        super.onDestroy()

        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction("restartservice");
        broadcastIntent.setClass(this, RestartUserActivity.class);
        this.sendBroadcast(broadcastIntent);
    }
}
1

There are 1 answers

0
Rudolf On

in android there are 3 ways for get location. They are GPS, Network and Google. Actually Network use Google's APIs, but if you want to get your current location without any maps and internet connection you need to implement GPS_PROVIDER

If present, this provider determines location using GNSS satellites. The responsiveness and accuracy of location fixes may depend on GNSS signal conditions. However, GPS can be slower to acquire a location fix and may not work well indoors or in urban environments with tall buildings that obstruct satellite signals.

Check this tutorial