我有一个用于android7的java服务类,它应该提交设备的GPS位置。见下文。
我遇到的问题是Android Studio抛出了一个异常,比如“任务还没有完成”。
我还尝试将其作为单独的线程运行。
如何解决这个问题?
protected void getLocation() {
// Create the location request to start receiving updates
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
// Create LocationSettingsRequest object using location request
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
// Check whether location settings are satisfied
// https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
SettingsClient settingsClient = LocationServices.getSettingsClient(this);
settingsClient.checkLocationSettings(locationSettingsRequest);
// new Google API SDK v11 uses getFusedLocationProviderClient(this)
fusedLocationClient = getFusedLocationProviderClient(this);
// Approach 1
setGpsLocation(fusedLocationClient);
// Approach 2
new Thread(new Runnable() {
@Override
public void run() {
try {
setGpsLocation(fusedLocationClient);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();}
private void setGpsLocation(FusedLocationProviderClient f) {
Location location = f.getLastLocation().getResult();
StringBuilder sb = new StringBuilder();
sb.append("<Data>");
sb.append(" <UserId>" + userId + "</UserId>");
sb.append(" <Type>GpsLocation</Type>");
sb.append(" <Longitude>" + location.getLongitude() + "</Longitude>");
sb.append(" <Latitude>" + location.getLatitude() + "</Latitude>");
sb.append(" <DateTime>" + sdf.format(new Date()) + "</DateTime>");
sb.append("</Data>");
}}
发布于 2019-12-16 19:36:21
getLastLocation()方法返回一个任务对象。Task对象表示异步操作(通常是获取某个值的操作,在本例中是Location对象)。您可以从location对象中检索位置的纬度和经度。在极少数情况下,当位置不可用时,location对象为null。
Task类提供了用于添加成功和失败侦听器的方法。如果操作成功,成功的监听器将传递所需的对象。如果操作不成功,则失败监听器将传递异常。
mFusedLocationClient.getLastLocation().addOnSuccessListener(
new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
mLastLocation = location;
}
}
});
mFusedLocationClient.getLastLocation().addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, "onFailure: ", e.printStackTrace());
}
}
);https://stackoverflow.com/questions/59355410
复制相似问题