我正在尝试实现getLastLocation().addOnSuccessListener
,如此处记录的那样:https://developer.android.com/training/location/retrieve-current#last-known,但在我的情况下,是在JobScheduler定期运行的JobService中。
这是我的jobService中有意义的部分:
public class PeriodicJob extends JobService {
final String TAG = "BNA.Job";
private FusedLocationProviderClient fusedLocationClient;
@Override
public void onCreate() {
super.onCreate();
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
Log.i(TAG, "onCreate");
}
@Override
public boolean onStartJob(JobParameters params) {
Log.d(TAG, "Job started..."); // logs every 15mins
fusedLocationClient.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) {
Log.d(TAG, "got Location: " + location);
Log.d(TAG, "Accuracy:" + location.getAccuracy()+", LON:"
+location.getLongitude() + ", LAT:" + location.getLatitude());
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
(...) // never runs
});
return true;
}
运行此命令(编译正常)时,我得到:Caused by: java.lang.ClassCastException: (...)PeriodicJob cannot be cast to java.util.concurrent.Executor
我查看了Android app crashes on firebase phone authentication和Can't cast this into Executor in google reCAPTCHA,但仍然无法正常工作。像第二个问题的答案所暗示的那样,仅调用.addOnSuccessListener(new OnSuccessListener<Location>()
不会引发任何错误,但是代码永远不会执行(至少没有写入日志)。
如何使onSuccess的电话正常工作?
编辑:实际上,它一直都在工作(没有第一个参数),我忽略了检测返回空位置(我没想到的)的情况。感谢Mike M。!