OK, first first. AsyncTask, which comes with Android, should not mute your application or cause it to crash. AsyncTasks runs in a thread pool, in which no more than 5 threads are actually running at a time. Although you can queue up many tasks that will be performed, only 5 of them are performed at a time. Running them in the background thread, they should not affect your application at all, they should just work smoothly.
Using AsyncTaskLoader will not solve your problem if you are unsatisfied with the performance of the AsyncTask loader. AsyncTaskLoader simply takes the bootloader interface and marries AsyncTask. Therefore, it essentially displays onLoadFinished -> onPostExecute, onStart -> onLoadInBackground. So this is the same.
We use the same image downloader code for our application, which forces the async to queue threadpool every time we try to load an image. In the Google example, they map the image to its async task so that they can cancel the async task if they try to reuse the image in some adapter. You should go for a similar strategy. You must link your image to the async task by loading the image in the background. When you have a fragment that is not displayed, you can cycle through the images associated with this fragment and cancel the download task. Just using AsyncTask.cancel () should work pretty well.
You should also try to implement a simple image caching mechanism, which will show an example of an asynchronous image representation. We just create a static hash file that comes from url -> weakreference. Thus, images can be recycled when they should be, because they are only held when there is a weak link.
Here is the image loading scheme we make
public class LazyLoadImageView extends ImageView { public WeakReference<ImageFetchTask> getTask() { return task; } public void setTask(ImageFetchTask task) { this.task = new WeakReference<ImageFetchTask>(task); } private WeakReference<ImageFetchTask> task; public void loadImage(String url, boolean useCache, Drawable loadingDrawable){ BitmapDrawable cachedDrawable = ThumbnailImageCache.getCachedImage(url); if(cachedDrawable != null){ setImageDrawable(cachedDrawable); cancelDownload(url); return; } setImageDrawable(loadingDrawable); if(url == null){ makeDownloadStop(); return; } if(cancelDownload(url)){ ImageFetchTask task = new ImageFetchTask(this,useCache); this.task = new WeakReference<ImageFetchTask>(task); task.setUrl(url); task.execute(); } ...... public boolean cancelDownload(String url){ if(task != null && task.get() != null){ ImageFetchTask fetchTask = task.get(); String downloadUrl = fetchTask.getUrl(); if((downloadUrl == null) || !downloadUrl.equals(url)){ fetchTask.cancel(true); return true; } else return false; } return true; } }
So, just rotate the images that are in your fragment, and then undo them when your fragment is hiding and show them when your fragment is visible.
Brian griffey
source share