【发布时间】:2018-12-19 19:06:01
【问题描述】:
如何使后台刷新间隔为 5 秒。根据我的代码,当我发布新名称时它不会显示,因此当我重新打开应用程序时它会显示,所以我需要自动刷新。
我应该改变什么或应该添加什么。
MainActivity
public class MainActivity extends AppCompatActivity {
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listViewHeroes);
//calling the method to display the heroes
getHeroes();
}
private void getHeroes() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
.build();
Api api = retrofit.create(Api.class);
Call<List<Hero>> call = api.getHeroes();
call.enqueue(new Callback<List<Hero>>() {
@Override
public void onResponse(Call<List<Hero>> call, Response<List<Hero>> response) {
List<Hero> heroList = response.body();
//Creating an String array for the ListView
String[] heroes = new String[heroList.size()];
//looping through all the heroes and inserting the names inside the string array
for (int i = 0; i < heroList.size(); i++) {
heroes[i] = heroList.get(i).getName();
}
//displaying the string array into listview
listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, heroes));
}
@Override
public void onFailure(Call<List<Hero>> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
【问题讨论】:
-
后台刷新是指在活动可见时自动刷新,或者即使活动没有运行也刷新数据。
-
是的,当活动可见时自动刷新
标签: android rest api android-studio-3.0