目前,我正在建立一个应用程序,将显示用户最近的预测。为了进行api调用,我必须提供经度和纬度作为参数。目前,我已经编写了一些关于获取语言度和经度的代码,但是我没有收到正确的数据。当我在mainactivity中编写这些方法时,首先,经度和纬度等于0.0,大约两秒钟后,它就能够获得正确的数据。我应该冻结应用程序直到locationmanage获得正确的数据,还是应该在其他地方调用这些方法?我应该给他们打电话吗?
正在检查权限
if (ContextCompat.checkSelfPermission(
getApplicationContext(), Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
Manifest.permission.INTERNET, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
}, 1);
}
}
}
OnLocation已更改
@Override
public void onLocationChanged(@NonNull Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
Log.i(TAG, "onLocationChanged: "+mLatitude+" "+mLongitude);
}
在存储库中
public static double mLatitude = MainActivity.mLatitude;
public static double mLongitude = MainActivity.mLongitude;
public ForecastRepository(){
mApi = RetrofitBuilder.makeCall();
}
public MutableLiveData<ForecastModel> testCall() {
MutableLiveData<ForecastModel> data = new MutableLiveData<>();
//TODO temporary values such as latitude/longitude in api call
mApi.test(mLatitude, mLongitude, "metric", API_KEY).enqueue(new Callback<ForecastModel>() {
@Override
public void onResponse(Call<ForecastModel> call, Response<ForecastModel> response) {
if (!response.isSuccessful()){
Log.i(TAG, "onResponse: "+ response.code());
}
Log.i(TAG, "onResponse: successful "+mLatitude+" "+mLongitude);
data.setValue(response.body());
}
@Override
public void onFailure(Call<ForecastModel> call, Throwable t) {
Log.i(TAG, "onFailure: "+t.getMessage());
}
});
return data;
}
}
1条答案
按热度按时间xxhby3vn1#
正确的方法是
LocationRepository
在那里你都会在一个background thread
设备位置的名称。创建
MutableLiveData
在viewmodel中指定位置。然后使用postvalue()或setvalue()更新其值。
为这个mutablelivedata编写一个公共getter。此存储库将成为您的位置api。
那么您的viewmodel应该
call the method
并将其结果分配给viewmodel的livedata变量。那么在你的活动中
observe
viewmodel的livedata。并进行api调用。