Java Fusedlocation RequestLocationUpdate在后台不工作
我正在尝试从我的应用程序打印出我的位置。它在前景中运行良好,但一旦我移动到背景,它就停止打印。我创建了一个location类,即它是一个普通类,而不是一个活动或片段。 我从一个片段将类作为服务启动:Java Fusedlocation RequestLocationUpdate在后台不工作,java,android,fusedlocationproviderapi,android-fusedlocation,Java,Android,Fusedlocationproviderapi,Android Fusedlocation,我正在尝试从我的应用程序打印出我的位置。它在前景中运行良好,但一旦我移动到背景,它就停止打印。我创建了一个location类,即它是一个普通类,而不是一个活动或片段。 我从一个片段将类作为服务启动: Intent intent = new Intent(getActivity(), LocationData.class); getContext().startService(intent); LocationData locationData = new LocationData(this.re
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;
}
}
没有打印出任何错误