目前,我正在构建一个应用,该应用将向用户显示最近的预测。为了进行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);
}
}
}
onLocationChanged @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;
}
}
最佳答案
正确的方法是使用LocationRepository
在设备位置的background thread
中进行所有提取。
在ViewModel中创建一个MutableLiveData
,您将在其中分配位置。
然后使用postValue()或setValue()更新其值。
为此MutableLiveData编写一个公共(public) getter 。该存储库将是您的位置API。
然后,您的ViewModel应该为存储库的call the method
并将其结果分配给ViewModel的LiveData变量。
然后在Activity observe
中添加ViewModel的liveData。
并进行您的API调用。
关于java - MVVM-我应该在哪里调用用户位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65499145/