首页 > 解决方案 > 定位服务更新慢

问题描述

我在我的应用程序中实现了一个使用 FusedLocationProviderClient 的定位服务,以便在开始跟踪时每 1 秒跟踪一次我的位置。跟踪工作正常,但在主动跟踪约 10-15 分钟后,更新变慢,每 3 秒更新一次位置,20-30 分钟后..约 5 秒。这段时间之后,该应用程序变得生涩。每秒将位置、高度、方位和时间记录到一个数据库(房间数据库)中,该数据库保持打开状态,直到停止跟踪。有人有类似的问题吗?由于保存了许多数据或FusedLocationProviderClient独立制作的某种“保存模式”,它是否可以连接到手机内存?我正在三星 S9+ 上尝试,它应该没有内存问题。有没有更轻的方法?我在定位服务的代码下方发布:

public class LocationService extends Service {
    FusedLocationProviderClient fusedLocationProviderClient;
    LocationCallback locationCallback;

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

    @Override
    public void onCreate() {
        super.onCreate();
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                Intent intent = new Intent("ACT_LOC");
                intent.putExtra("latitude", locationResult.getLastLocation().getLatitude());
                intent.putExtra("longitude", locationResult.getLastLocation().getLongitude());
                intent.putExtra("altitude", locationResult.getLastLocation().getAltitude());
                intent.putExtra("precision", locationResult.getLastLocation().getAccuracy());
                intent.putExtra("speed", locationResult.getLastLocation().getSpeed());
                intent.putExtra("time", locationResult.getLastLocation().getTime());
                intent.putExtra("bearing",locationResult.getLastLocation().getBearing());
                sendBroadcast(intent);
            }
        };
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        requestLocation();
        return super.onStartCommand(intent, flags, startId);
    }

    private void requestLocation() {
        LocationRequest locationRequest = new LocationRequest();
        locationRequest.setInterval(1000);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
    }
}

标签: javagpsissue-trackinglocation-services

解决方案


看起来你有某种泄漏。就像每次获得位置时创建新的位置更新订阅一样。您可以检查内存泄漏或添加日志记录,以验证处理位置更新的所有代码是否针对每个新位置只运行一次。


推荐阅读