我正在开发一个Android应用程序,其中有一个功能,使用asynctask加载一些图像。我想如果我可以保存这些图像作为缓存我可以提高应用程序的性能,因为我正在加载大量的图像。我怎样才能做到这一点?如何在我的Android应用程序中保留缓存?
我的班级
public class MovieFragment extends Fragment {
private ViewPager viewPager;
private PageAdapter pageAdapter;
private ViewPageAdapter adapter;
private ArrayList<BaseElement> filmCategory;
private Fragment fragment;
private Activity activity;
private CommonVariable commonVariable;
private FilmCategory category;
private Dialog dialog;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.movie_fragment, container, false);
fragment = this;
activity = this.getActivity();
commonVariable = (CommonVariable) activity.getApplication();
viewPager = (ViewPager) view.findViewById(R.id.news_page_viewpager);
dialog = new Dialog(this.getActivity(),
android.R.style.Theme_Translucent_NoTitleBar);
new BackGround().execute();
return view;
}
public class BackGround extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
filmCategory = JSONServices.getCategory();
return null;
}
@Override
protected void onPostExecute(Void result) {
commonVariable.setCategory(filmCategory);
if (filmCategory != null) {
pageAdapter = new PageAdapter(
fragment.getChildFragmentManager(), filmCategory,
activity);
viewPager.setAdapter(pageAdapter);
} else {
Toast.makeText(activity, "No Active Internet Connection",
Toast.LENGTH_LONG).show();
}
dialog.dismiss();
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
// commonVariable.setFilmDetails((FilmCategory)
// category.getFilm().get(position));
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
super.onPostExecute(result);
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog.setContentView(R.layout.dialog);
dialog.show();
super.onPreExecute();
}
}
答案 0 :(得分:0)
如果您从服务器下载图像,那么我认为Volley库会帮助您。它将删除样板代码并且易于阅读它也支持缓存。如果要实现缓存,请按this链接。请避免asyctask它将无法生存配置更改。使用asynctaskLoader: - )
答案 1 :(得分:0)
似乎最简单的方法是使用第三方库,例如Picasso,Universal Image Loader或Volley
在尝试实现图像缓存系统之前,我会先检查一下。在大多数情况下,这三个选项中的一个将处理您需要完成的所有事情。