Do not reparent the SC when package is already realeased

If we pass a copy of the surface package, we can release the original,
but we need to check that in this case the surface control doesn't get
reparented to null since the SurfaceView using the copy might already
use the surface.

Test: atest CtsWindowManagerDeviceTestCases:SurfaceControlViewHostTests#testTransferSurfacePackage
Bug: 181757194
Change-Id: Ibf084aa70f3821e7dc82fe45b194c07f307ebe1e
diff --git a/core/java/android/view/SurfaceView.java b/core/java/android/view/SurfaceView.java
index 2fce434..6b0bb9d 100644
--- a/core/java/android/view/SurfaceView.java
+++ b/core/java/android/view/SurfaceView.java
@@ -571,7 +571,10 @@
         // recreate this Surface, so only release it when we are fully
         // detached.
         if (mSurfacePackage != null) {
-            mTmpTransaction.reparent(mSurfacePackage.getSurfaceControl(), null).apply();
+            final SurfaceControl sc = mSurfacePackage.getSurfaceControl();
+            if (sc != null && sc.isValid()) {
+                mTmpTransaction.reparent(sc, null).apply();
+            }
             mSurfacePackage.release();
             mSurfacePackage = null;
         }
@@ -1826,7 +1829,7 @@
      */
     public void setChildSurfacePackage(@NonNull SurfaceControlViewHost.SurfacePackage p) {
         final SurfaceControl lastSc = mSurfacePackage != null ?
-            mSurfacePackage.getSurfaceControl() : null;
+                mSurfacePackage.getSurfaceControl() : null;
         if (mSurfaceControl != null && lastSc != null) {
             mTmpTransaction.reparent(lastSc, null).apply();
             mSurfacePackage.release();
@@ -1839,8 +1842,11 @@
 
     private void reparentSurfacePackage(SurfaceControl.Transaction t,
             SurfaceControlViewHost.SurfacePackage p) {
-        initEmbeddedHierarchyForAccessibility(p);
         final SurfaceControl sc = p.getSurfaceControl();
+        if (sc == null || !sc.isValid()) {
+            return;
+        }
+        initEmbeddedHierarchyForAccessibility(p);
         final SurfaceControl parent;
         if (mUseBlastAdapter) {
             parent = mBlastSurfaceControl;