android - 从服务中的 FusedLocation 获取最后一个位置
问题描述
我试图在我的服务中获取最后位置(),女巫每分钟都在开始。如我所见, fusedLocation 需要Activity
or Executor
in .addOnSuccessListener()
。我怎样才能在服务中获得它?
LocationCheckService.class
public class LocationCheckService extends Service{
private FusedLocationProviderClient mFusedLocationClient;
@Override
public void onCreate() {
super.onCreate();
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
}
}
});
}
@SuppressLint("MissingPermission")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
解决方案
您不需要 GoogleApiClient -
首先在 gradle 添加 -
implementation 'com.google.android.gms:play-services-location:15.0.0'
在 Android 清单中 -
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
而不是创建一个服务来获取位置更新 -
public class LocationUpdateService extends Service {
private FusedLocationProviderClient client;
private LocationRequest locationRequest;
@Override
public void onCreate() {
super.onCreate();
client = LocationServices.getFusedLocationProviderClient(this);
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(0);
locationRequest.setFastestInterval(0);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
client.requestLocationUpdates(locationRequest, locationCallback, null);
} catch (SecurityException ignore) {
Log.e("AppLocationService", "SecurityException - " + ignore.toString(), ignore);
}
return START_STICKY;
}
private final LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() != 0) {
Location location = locationList.get(0);
Log.e("AppLocationService", "Latitude - " +location.getLatitude()+", longitude - " +location.getLongitude() );
}
}
};
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
}
要获取活动更新,您可以使用 LocalBroadCast 或可以在活动中使用的相同代码
注意:不要忘记在 23 岁以上获得许可
推荐阅读
- regex - 用 grep 计算包含子字符串的单词数
- video - 颤动中垂直滚动视图中的视频
- javascript - 如何使用 javascript 将数据流式传输到 csv 文件
- sql - 使用案例选择特定记录,好像
- arduino - 如何使用 RC522 模块对带有网站 URL 的 NFC 芯片进行编码
- javascript - 如何使用 Webkit Animation 使一个圆圈在另一个圆圈内旋转
- angular - NgRx 没有跳过错误时的“成功”操作
- x86 - 屏障/栅栏和获取、释放语义是如何在微架构上实现的?
- r - 如何将具有不同长度元素的列表转换为数据框
- python - 如何按大小连续对值进行评分?