这是我的代码:
private void getUserData(){
//create Retrofit instance
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create());
Retrofit retrofit = builder.build();
//get client & call object for the request
APIService userService = retrofit.create(APIService.class);
Map<String, Object> map = new HashMap<>();
map.put("device_id", Utils.GetDeviceID(DashboardActivity.this));
Call call = userService.getUser(map);
//execute network request
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if(response.isSuccessful() && response.body() != null){
response.body();
UserDataManager.$().setUserDataResponse(new com.google.gson.Gson().toJson(response.body()));
if(UserDataManager.$().getUserData() != null){
Log.d(TAG, "USER ID: " + UserDataManager.$().getUserData().getId());
}
}
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
}
问题:如何每5秒调用一次这个方法,检查是否有新数据来自后端?
很高兴提出建议和提示,谢谢
最佳答案
RxAndroid 在这种情况下会非常有用。您可以像这样创建循环
Subscription subscription = Observable.interval(1000, 5000,
TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Long>() {
public void call(Long aLong) {
// here is the task that should repeat
}
});
如果你想停止循环,只需调用
subscription.unsubscribe()
关于java - 安卓,改造 2 : How to make calls every 5 second?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49718396/