gpt4 book ai didi

java - Android 7服务gps更新

转载 作者:行者123 更新时间:2023-12-01 19:20:51 25 4
gpt4 key购买 nike

我有一个适用于 android 7 的 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>");

}

}

最佳答案

getLastLocation() 方法返回一个 Task 对象。 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());

}
}
);

关于java - Android 7服务gps更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59355410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com