Missing location update from the device

39 Views Asked by At

I have written a background service in the app to track the location of the driver. Sometimes I can see the update of location is frequent and sometimes it is not. I have looked for the problem which is causing this issue and failed to identify it. As is it a very important and core functionality to track the location of the driver it will be very helpful if anyone guides me through the solution.

[![Location update image reference][1]][1]

Below is the code 

Permission:

`<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />`

   `public class FetchLocation extends Service {
    private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 25000;
    private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
            UPDATE_INTERVAL_IN_MILLISECONDS / 2;
    private FusedLocationProviderClient mFusedLocationClient;
    Context context = this;
    private LocationCallback mLocationCallback;

    @Override
    public void onCreate() {
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        displayLocationUpdateNotification();
        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(@NonNull LocationResult locationResult) {
                super.onLocationResult(locationResult);
                onNewLocation(locationResult.getLastLocation());
            }
        };

        if (checkPermission(this)) {
            setLocationSetting();
            getLastLocation();
        }
    }

    private void getLastLocation() {
        try {
            mFusedLocationClient.getLastLocation()
                    .addOnCompleteListener(new OnCompleteListener<Location>() {
                        @Override
                        public void onComplete(@NonNull Task<Location> task) {
                            if (task.isSuccessful() && task.getResult() != null) {
                                mLocation = task.getResult();
                                onNewLocation(mLocation);
                            } else {
                                Log.d(getClass().getName(), "Failed to get location.");
                            }
                        }
                    });
        } catch (SecurityException unlikely) {
            Log.d(getClass().getName(), "Lost location permission." + unlikely);
        }
    }

    private void setLocationSetting() {
        LocationRequest locationRequest = new LocationRequest.Builder(5000)
                .setGranularity(Granularity.GRANULARITY_FINE)
                .setPriority(Priority.PRIORITY_HIGH_ACCURACY)
                .setMinUpdateDistanceMeters(20)
                .setMinUpdateIntervalMillis(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS)
                .build();

        LocationSettingsRequest locationSettingsRequest = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest)
                .build();
        SettingsClient settingsClient = LocationServices.getSettingsClient(context);
        settingsClient.checkLocationSettings(locationSettingsRequest).addOnCompleteListener(new      OnCompleteListener<LocationSettingsResponse>() {
            @Override
            public void onComplete(@NonNull Task<LocationSettingsResponse> task) {
                if (task.isSuccessful() && task.getResult() != null) {
                    if(checkPermission(context)) {
                        mFusedLocationClient.requestLocationUpdates(locationRequest, mLocationCallback, Looper.myLooper());
                    }

                }
            }
        });
    }

   private void displayLocationUpdateNotification() {
        try {

            NotificationManager notif = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

            int notification_id = 4001;
            Intent intent = new Intent(context, Splash.class);
            intent.setAction(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
            stackBuilder.addParentStack(Dashboard.class);
            stackBuilder.addNextIntent(intent);

            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(notification_id,
                    PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);

            RemoteViews expandedView = new RemoteViews(context.getPackageName(), R.layout.fcm_location_update);

            Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.hornoklogobig);

            final String CHANNEL_ONE_NAME = "Location updates";

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
                        CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_HIGH);
                notificationChannel.setShowBadge(true);
                notificationChannel.setBypassDnd(true);
                notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
                notif.createNotificationChannel(notificationChannel);
            }

            Notification notification = new NotificationCompat.Builder(context, CHANNEL_ONE_ID)
                    .setSmallIcon(R.drawable.hornoklogonotificationlight)
                    .setLargeIcon(icon)
                    .setChannelId(CHANNEL_ONE_ID)
                    .setAutoCancel(false)
                    .setContentText("")
                    .setContentIntent(resultPendingIntent)
                    .setContentTitle("Location").build();

            notification.bigContentView = expandedView;

            expandedView.setTextViewText(R.id.desc, "Updating your location");

            notification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_NO_CLEAR;
            //notif.notify(notification_id, notification);
            startForeground(notification_id, notification);

        } catch (Exception e) {
            Timber.d(e);
        }
    }

}

Manifest code

 <service
            android:name=".services.FetchLocation"
            android:enabled="true"
            android:exported="true"
            android:foregroundServiceType="location" />`


  [1]: https://i.stack.imgur.com/aXujq.png
0

There are 0 best solutions below