首页 > 解决方案 > FLP中的位移和间隔

问题描述

我正在使用 Fused Location Api 来获取位置更新。当我将 15 分钟设置为时间间隔时,我每 15 分钟调用一次 onLocationChanged() 。当我将 50 米设置为 minimumDisplacement 时,直到用户从其原始位置移动 50 米时才会调用 onLocationChanged()。

但是我需要在经过 15 分钟或覆盖 50 米距离时调用 onLocationChanged()。

我写了两个LocationRequest和两个FusedLocationProviderBroadcastReceiver处理这个问题,但我的应用程序在移动用户方面运行良好,但在时间间隔内运行不正确。我可以在 15-20 分钟后获得位置,但几个小时后,时间间隔增加,之后我无法获得用户移动的位置,现在再次获得位置..

有时,我尝试获取位置:

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

在这种情况下,直到开始移动,我才能获得位置!

这是我的服务,该服务是前台服务:

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();
}
}

我可以使用setSmallestDisplacementOR获取位置setInterval吗?我想用我的代码,我写了间隔上的位移。

标签: androidservicelocationbroadcastreceiverfusedlocationproviderapi

解决方案


推荐阅读