Reputation: 213
I google a lot, but now I decided to ask..
My activity does only one simple thing - it downloads a picture from Internet using AsyncTask.
But there is a lot of problems, that I am not sure, how to solve..
1.] User rotates screen after AsyncTask have downloaded the picture.. How should I handle this screen rotation? Where to temporary save picture to be available after activity recreates?
I don't want to lock screen orientation (android:screenOrientation="landscape") or handle it by myself (android:configChanges="orientation")..
I just want to save the picture somewhere..
I know It can be done by using onRetainNonConfigurationInstance() and getLastNonConfigurationInstance(), but both are deprecated now. Bundle isn't appropriate for images, because it is made for String (Serializable) data. I can save picture to database or to file somewhere, but it is unnecessary. I read somewhere, that it can be done by Loader, but I don't know how? Is it possible?
2.] User rotates screen during AsyncTask is downloading a picture.
I want AsyncTask to continue with downloading. After download is complete, AsyncTask should save image to new (recreated) activity in onPostExecute method.
I think if AsyncTask is inner class of activity, it works..? But if I don't want it to be inner class I have to save reference to activity, for example in variable. But if I send reference to Activity as a parameter of constructor of AsyncTask, and Activity is recreated after screen rotation, the variable in AsyncTask does refer to original activity and so new one doesn't know about downloaded picture and it has to start download again..
Or is AsyncTask bad choice for downloading image? Should I use something else? Service?
So.. How to solve these problems? I am sure a lot of app developers have to solve this too.. But it is all Greek to me:(
Upvotes: 2
Views: 1661
Reputation: 11645
When your AsyncTask has finished downloading the image, save it to your application's cache directory. Persist the path to the saved image in a property on your Activity class. You can then override the onSaveInstanceState
method of your activity to pass the cached image path to itself during an orientation change. In your onCreate
method check the savedInstanceState
bundle for a saved image path. If that path exists, do not attempt to re-download the image. Instead, simply load the image from disk.
Upvotes: 1