1

I am using Fused Location Api to get location updates. When I set 15 minute as time interval then I got onLocationChanged() called after every 15 minute. And when I set 50 meter as minimumDisplacement then onLocationChanged() is not called until user moves 50 meter from its original position.

But I need to have onLocationChanged() called when either 15 minute passed or 50 meter distance covered.

I wrote two LocationRequest and two FusedLocationProvider and BroadcastReceiver for handling this problem but my applications worked good in moving user but not worked correct in time interval. I can get location after 15-20 minute but after some hours, the time interval increase and after that i can't get location that user moved and now get location again..

This is some times, I try get location:

2019-03-05 10:24:30.233
2019-03-05 10:39:59.147
2019-03-05 10:39:59.147
2019-03-05 10:51:16.783
2019-03-05 10:56:05.147
2019-03-05 11:01:16.407
2019-03-05 11:16:16.160
2019-03-05 11:31:19.197
2019-03-05 11:49:34.203
2019-03-05 12:46:24.280

And in this situation, I can't get locations until start moving!

This is my service and this service is forground:

public class LFPService extends Service {

private FusedLocationProviderClient mFLPClientTimeInterval;
private FusedLocationProviderClient mFLPClientDistanceInterval;
private LocationRequest mLocationRequestTimeInterval;
private LocationRequest mLocationRequestDistanceInterval;

private static final int NOTIFICATION_ID=123456789;

/**
 * The fastest rate for active location updates. Updates will never be more frequent
 * than this value.
 */
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =15*60*1000;//OfflineData.getGPSIntervalSetting(KITILApplication.getappContext())*1000;//15*60*1000;
        //OfflineData.getGPSIntervalSetting(KITILApplication.getappContext())*1000;

/**
 * The desired interval for location updates. Inexact. Updates may be more or less frequent.
 */
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS;//+60000;

private static final long MAX_WAITE_TIME=OfflineData.getTimeIntervalSetting(KITILApplication.getappContext())*1000;


private NotificationManager mNotificaionManager;
private static final String CHANNEL_ID = "channelLocation_01";

private static final String TAG = LFPService.class.getSimpleName();

private final IBinder mBinder = new LocalBinder();
private Handler mServiceHandler;


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

    mNotificaionManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.app_name);
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_DEFAULT);
        mNotificaionManager.createNotificationChannel(mChannel);
    }
    startForeground(AppConstant.SERVICE_NOTIFICATION_ID, getMyActivityNotification(this));

    mFLPClientTimeInterval = LocationServices.getFusedLocationProviderClient(this);
    mFLPClientDistanceInterval = LocationServices.getFusedLocationProviderClient(this);
    getLastLocation();

    createLocationRequest();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if(intent!=null&&intent.getAction()!=null&&intent.getAction().equals("LFPStartUpdateLoc")) {
        requestLocationUpdate();
    }else if(intent!=null&&intent.getAction()!=null&&intent.getAction().equals("LFPStopUpdateLoc")){
        removeLocatinUpdate();
    }
    return START_STICKY;
}

@Override
public void onDestroy() {
    removeLocatinUpdate();
    super.onDestroy();
}

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

public class LocalBinder extends Binder {
    public LFPService getService() {
        return LFPService.this;
    }
}

private void createLocationRequest() {
    //Location Request for Time Interval
    mLocationRequestTimeInterval = new LocationRequest();
    mLocationRequestTimeInterval.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequestTimeInterval.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequestTimeInterval.setSmallestDisplacement(0);
    mLocationRequestTimeInterval.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    //Location Request for Distance Interval
    mLocationRequestDistanceInterval = new LocationRequest();
    mLocationRequestDistanceInterval.setInterval(0);
    mLocationRequestDistanceInterval.setFastestInterval(0);
    mLocationRequestDistanceInterval.setSmallestDisplacement(50);
    mLocationRequestDistanceInterval.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

public void requestLocationUpdate() {
    try {
        mFLPClientTimeInterval.requestLocationUpdates(mLocationRequestTimeInterval, getIntervalPendingIntent());
        mFLPClientDistanceInterval.requestLocationUpdates(mLocationRequestDistanceInterval,getDisplacementPendingIntent());// mLocationCallback,null);
        if (AppConstant.ENABLE_LOG_APPLICATION)
            HelperMethods.recordLogOnDB("LFPService/requestLocationUpdate/System Date= " + HelperUtility.convertDateToString(new Date()));
    }catch (SecurityException ex){
        //Turn off permission
    }
}

public  void removeLocatinUpdate(){
    if (AppConstant.ENABLE_LOG_APPLICATION)
        HelperMethods.recordLogOnDB("LFPService/removeLocationUpdate/System Date= " + HelperUtility.convertDateToString(new Date()));
    mFLPClientTimeInterval.removeLocationUpdates(getIntervalPendingIntent());
    mFLPClientDistanceInterval.removeLocationUpdates(getDisplacementPendingIntent());
}

private PendingIntent getIntervalPendingIntent(){
    Intent intent=new Intent(this,LFPIntervalUpdateBroadcastReceiver.class);
    intent.setAction(LFPIntervalUpdateBroadcastReceiver.ACTION_PROCESS_UPDATES);
    return PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
}

private PendingIntent getDisplacementPendingIntent(){
    Intent intent=new Intent(this,LFPDisplacementBroadcastReceiver.class);
    intent.setAction(LFPDisplacementBroadcastReceiver.ACTION_PROCESS_UPDATES);
    return PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
}

private void getLastLocation() {
    try {
        mFLPClientTimeInterval.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                permissionStatus = true;
                if (task.isSuccessful() && task.getResult() != null) {
                    mLocation = task.getResult();
                }
            }
        });
        mFLPClientDistanceInterval.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                permissionStatus = true;
                if (task.isSuccessful() && task.getResult() != null) {
                    mLocation = task.getResult();
                }
            }
        });
    } catch (SecurityException ex) {
        permissionStatus = false;
    }
}


public static Notification getMyActivityNotification(Context context) {
    Intent intentMain = new Intent(context, CategoryActivity.class);
    intentMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentMain, 0);

    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationCompat.Builder builder;
    if (AppConstant.DEBUG_MODE)
        Log.e("TEST=Noti Start service", "createNotification");

    Uri alarmSound = Settings.System.DEFAULT_NOTIFICATION_URI;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String channelId = "KITIL_LFPService_id";
        CharSequence channelName = "KITIL_LFPService";
        int importance = NotificationManager.IMPORTANCE_LOW;
        NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
        mNotificationManager.createNotificationChannel(notificationChannel);
        builder = new NotificationCompat.Builder(context, channelId);
        Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
                R.drawable.ic_launcher);
        builder.setContentTitle("")
                .setTicker("")
                .setContentText("" + OfflineData.getCartableCount(context) + ".")
                .setSmallIcon(R.drawable.ic_launcher)
                .setLargeIcon(
                        Bitmap.createScaledBitmap(icon, 128, 128, false))
                .setDefaults(Notification.DEFAULT_ALL).setContentIntent(pendingIntent)
                .setOngoing(true)
                .build();
        if (AppConstant.DEBUG_MODE)
            Log.e("TEST=Noti Start service", "apiO");
    } else {
        builder = new NotificationCompat.Builder(context, null);
        Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
                R.drawable.ic_launcher);
        builder.setContentTitle("")
                .setTicker("")
                .setContentText(" " + OfflineData.getCartableCount(context) + ".")
                .setSmallIcon(R.drawable.ic_launcher)
                .setLargeIcon(
                        Bitmap.createScaledBitmap(icon, 128, 128, false))
                .setDefaults(Notification.DEFAULT_ALL).setContentIntent(pendingIntent)
                .setOngoing(true)
                .build();
        if (AppConstant.DEBUG_MODE)
            Log.e("TEST=Noti Start service", "apiBelowO");
    }
    //mNotificationManager.notify(AppConstant.SERVICE_NOTIFICATION_ID, builder.build());
    return builder.build();
}
}

Can I get location with setSmallestDisplacement OR setInterval? I think with my code, I wrote displacement over interval.

Zumbarlal Saindane
  • 1,199
  • 11
  • 24
  • Anyone can't answer to my question? Please help me i should solve this problem – Fahimeh Hashemian Mar 06 '19 at 07:35
  • The doc says `Any previous LocationRequests registered on this LocationListener will be replaced`. Seems like your distance interval request is overriding time interval request. – Binary Baba Mar 06 '19 at 08:21

0 Answers0