Fix HardwareRenderers becoming invalidated by TRIM

Fixes: 335646931
Test: repro steps in bug
(cherry picked from https://googleplex-android-review.googlesource.com/q/commit:254972cf117af611b3ed27e46657344a162616a9)
Merged-In: I6b22d202b71effa1a7136a20f51b38732d0fde74
Change-Id: I6b22d202b71effa1a7136a20f51b38732d0fde74
diff --git a/libs/hwui/renderthread/CanvasContext.cpp b/libs/hwui/renderthread/CanvasContext.cpp
index 1d03301..ad864ec 100644
--- a/libs/hwui/renderthread/CanvasContext.cpp
+++ b/libs/hwui/renderthread/CanvasContext.cpp
@@ -994,7 +994,15 @@
 }
 
 void CanvasContext::onContextDestroyed() {
-    destroyHardwareResources();
+    // We don't want to destroyHardwareResources as that will invalidate display lists which
+    // the client may not be expecting. Instead just purge all scratch resources
+    if (mRenderPipeline->isContextReady()) {
+        freePrefetchedLayers();
+        for (const sp<RenderNode>& node : mRenderNodes) {
+            node->destroyLayers();
+        }
+        mRenderPipeline->onDestroyHardwareResources();
+    }
 }
 
 DeferredLayerUpdater* CanvasContext::createTextureLayer() {