[英]MVVM - where should I call for user location?
目前,我正在構建一個應用程序,它將顯示用戶最近的預測。 為了進行 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 編寫一個公共 getter。 此存儲庫將是您的位置 API。
然后,您的 ViewModel 應該call the method
並將其結果分配給 ViewModel 的 LiveData 變量。
然后在您的 Activity 中observe
您的 ViewModel 的 liveData。
並撥打您的 API 電話。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.