Fix incorrect handling of pending activities

The full-screen activities in the SIM Toolkit application are expected
to keep staying in the screen even after TERMINAL RESPONSE is sent as
they might still be seen around the dialog launched by the next command.

StkAppService has a mechanism to keep such a "pending instance" and
finish it when the current session ends, but it cannot finish it
sometimes in the current implementation. If the current pending activity
is pushed out by the new one, the former one must be finished. It must
not have a reason to stay anymore at that time.

Bug: 38330809

Change-Id: Ib0399d0101c8555d6d0a3426df28db49349fef8e
diff --git a/src/com/android/stk/StkAppService.java b/src/com/android/stk/StkAppService.java
index a0ad403..85a6a72 100644
--- a/src/com/android/stk/StkAppService.java
+++ b/src/com/android/stk/StkAppService.java
@@ -577,10 +577,17 @@
                 handleCardStatusChangeAndIccRefresh((Bundle) msg.obj, slotId);
                 break;
             case OP_SET_ACT_INST:
-                Activity act = new Activity();
-                act = (Activity) msg.obj;
-                CatLog.d(LOG_TAG, "Set activity instance. " + act);
-                mStkContext[slotId].mActivityInstance = act;
+                Activity act = (Activity) msg.obj;
+                if (mStkContext[slotId].mActivityInstance != act) {
+                    CatLog.d(LOG_TAG, "Set activity instance - " + act);
+                    Activity previous = mStkContext[slotId].mActivityInstance;
+                    mStkContext[slotId].mActivityInstance = act;
+                    // Finish the previous one if it has not been finished yet somehow.
+                    if (previous != null && !previous.isDestroyed() && !previous.isFinishing()) {
+                        CatLog.d(LOG_TAG, "Finish the previous pending activity - " + previous);
+                        previous.finish();
+                    }
+                }
                 break;
             case OP_SET_DAL_INST:
                 Activity dal = new Activity();