熟悉堆栈溢出的程序员,我正在尝试使用retrofit2在viewpager.AddOnPageChangeListner上满足条件时发出网络请求,并在获取数据时显示进度对话框,问题是有时在屏幕上滑动,相同的网络请求被触发两次导致重复数据,有时它只是工作正常,我可以做出什么改变,以避免重复的网络请求。
mPager.addOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (imageUrls.size() - 1 == position & !nextCursor.equals("") & Util.isNetworkAvailable()) {
if (mResources != null){
mResources.clear();
}
// retrofit network request method
fetchImages(category, nextCursor);
}
if ((imageUrls.size() - 1 == position) & (Util.isNetworkAvailable() == false)) {
Toast.makeText(MainActivity.this, "No Internet " + imageUrls.size(), Toast.LENGTH_SHORT).show();
}
}
以下是改装请求方法声明
private void fetchImages(final String mCategory, final String mNextCursor) {
dialog.show();
call = ApiUtils.getImageService().getImageResource(mCategory, mNextCursor);
call.enqueue(new Callback<ImageResponse>() {
@Override
public void onResponse(Call<ImageResponse> call, Response<ImageResponse> response) {
imageResponse = response.body();
if (imageResponse.getResources() != null) {
mResources = imageResponse.getResources();
for (int i = 0; i < mResources.size(); i++) {
String imageUrl = mResources.get(i).getUrl();
String imageName = mResources.get(i).getPublicId();
Log.i("retrofitImageUrl",imageName);
imageUrls.add(imageUrl);
imageNames.add(imageName);
}
if (imageResponse.getNextCursor() != null) {
nextCursor = imageResponse.getNextCursor();
} else {
nextCursor = "";
}
imageInfo = ImageInfo.getInstance();
imageInfo.setImageUrls(imageUrls);
imageInfo.setPublicImageId(imageNames);
imageInfo.setNextcursor(nextCursor);
imageInfo.setCategoryType(mCategory);
String jSon = gson.toJson(imageInfo);
editor.putString("imageInfo",jSon);
editor.commit();
if (mPagerAdapter == null) {
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager(), mContext);
mPager.setAdapter(mPagerAdapter);
mPagerAdapter.notifyDataSetChanged();
}else {
mPagerAdapter.notifyDataSetChanged();
}
}else {
Toast.makeText(MainActivity.this,"No valid data was returned, please try again",Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
}
@Override
public void onFailure(Call<ImageResponse> call, Throwable t) {
dialog.dismiss();
Toast.makeText(MainActivity.this, "error:something went wrong", Toast.LENGTH_SHORT).show();
}
});
}
我能够通过使用Async任务修复此问题,并通过添加以下if条件将改进网络请求类型更改为同步
if (urls.size() - 1 == position & !nextCursor.equals("") & Util.isNetworkAvailable()) {
mResources.clear();
if ((imageDownloadAsyncTask.getStatus() != Status.RUNNING)&(imageDownloadAsyncTask.getStatus() != Status.PENDING)) {
asyncTask(category);
}
}
我真的想使用改造异步调用而不是单独的异步任务,但我如何使用改造来避免重复调用?我在改造中找不到call.pending或call.running方法。任何帮助将非常感谢!!
答案 0 :(得分:0)
在你的情况下,我认为你需要实现某种图像缓存系统。基本上,如果您已经下载了图像,则不会再拨打新电话再次下载图像。另外,如果您正在下载图像,还需要一些标记来知道。
我建议您使用已经提供所有这些的Picasso,Glide或ImageDownloader。