java Android 7服务gpsupdate
我有一个安卓 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/安卓/reference/com/google/安卓/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>");
}
}
# 1 楼答案
getLastLocation()方法返回一个任务对象。任务对象表示异步操作(通常是获取某个值的操作,在本例中是位置对象)。从location对象检索位置的纬度和经度。在极少数情况下,当位置不可用时,位置对象为空
任务类提供了添加成功和失败侦听器的方法。如果操作成功,成功侦听器将传递所需的对象。如果操作不成功,失败侦听器将传递异常