fusedlocation-requestlocationupdates在后台不工作

mpgws1up  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(244)

我正试图从我的应用程序打印出我的位置。它在前台工作得很好,但当我移到后台时,它就停止打印了。我创建了一个location类,也就是说,它是一个普通类,而不是一个活动或片段。我从一个片段将类作为服务启动:

Intent intent = new Intent(getActivity(), LocationData.class);
getContext().startService(intent);
LocationData locationData = new LocationData(this.requireContext());

下面的代码是location类。

public class LocationData extends Service implements LocationListener {

    public LocationData() {}

    private Double mLatitude;
    private Double mLongitude;

    public LocationData(Context context) {

        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        LocationRequest mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(10000);
        mLocationRequest.setFastestInterval(1000);

        LocationCallback locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                if (locationResult == null) {
                    Log.i(LOG_LINE, "NULLAR");
                    return;
                }
                Log.i(LOG_LINE, "onLocationResult");
                Log.i(LOG_LINE, locationResult.getLastLocation().toString());
            }
        };

        FusedLocationProviderClient fusedLocation = LocationServices.getFusedLocationProviderClient(context);

        fusedLocation.getLastLocation().addOnSuccessListener(location -> {
            if (location == null) {
                Log.i(LOG_LINE, "!onSuccess");
            } else {
                Log.i(LOG_LINE, "onSuccess");
            }
        });

        Intent intent = new Intent(context, this.getClass());
        PendingIntent pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        fusedLocation.requestLocationUpdates(mLocationRequest, pi);
        fusedLocation.requestLocationUpdates(mLocationRequest, locationCallback, Looper.getMainLooper());
    }

    public Double getLatitude() { return mLatitude; }
    public Double getLongitude() { return mLongitude; }

    @Override
    public void onLocationChanged(Location location) {
        mLatitude = location.getLongitude();
        mLongitude = location.getLatitude();
        Log.i(LOG_LINE, mLatitude.toString());
        Log.i(LOG_LINE, mLongitude.toString());
    }

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

没有打印错误。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题