Hello,
I am working on building an application that utilizes several images. Because the app is intended to be cross platform (Android and iOS), I have been using Xamarin Forms to create the application. After building several pages and controls, I have encountered a problem which I do not fully understand. I am going to focus on the Android platform for the remainder of this post, because I am currently unable to test on iOS.
When navigating from a page (dub it the home page) to another page (dub it the image page), I will run into an OutOfMemoryError after performing the transition a number of times. Where the transition involves using Xamarin Forms' built in NavigationPage with the page's Navigation.PushAsync command to move to the image page and the device's back button to return to the home page. The first few times, the page will load correctly and behave as expected. Unfortunately, it appears that the memory resources allocated for the image page are not freed when I navigate back to the home page (using the back button). I anticipate these resources SHOULD be freed, but perhaps I need to do something to explicitly release this instance of image page (and the corresponding HUGE amount of image data). Since the memory resources are never freed, after I do the transition a number of times (the number fluctuates based on the device, which images are on the page, etc. obviously), the application will crash with an OutOfMemoryError. I understand that the GC will not immediately free the resources, but it should free the resources before giving up and crashing (yes?).
My question: what do I need to do in order to release the memory used by a Xamarin.Forms Page when that page leaves the navigation stack? (I am not explicitly calling Navigation.PopAsync but I imagine the NavigationPage's implementation of the back button does something of that nature.)
I have created a tiny sample project which demonstrates the behavior I have discussed above. The project is a stripped down version of Xamarin's FormsGallery (from their Github), in which I have updated the ImageDemoPage to display 2 fairly large images which I added to the Android project. Note that I have not been testing on iOS or Windows Phone so I did not bother to even tailor this sample to those platforms. The sample has a home page (the list of pages) and an image page (ImageDemoPage). I expect to be able to visit ImageDemoPage infinitely many times (because whenever it leaves the view, every resource it used should become available to be reused). I am unable to visit ImageDemoPage infinitely many times (my Nexus 7 crashes within a dozen visits, my Android phone crashes within 5). The device output log includes GC information which shows the heap is continually growing, and does not shrink (noticeably). Either I am doing something wrong or my understanding is flawed. Any feedback would be much appreciated!
Thanks