[CPMS] Eliminating extra signal sent after shutdown happened

Test: atest CarPowerManagementServiceTest
Bug: 120958574
Change-Id: I9435bfbef33d6aababe2b1acb38ee32a446f636d
(cherry picked from commit e0f646c50e51e7c7e2033128efd4cc8c4978a6a1)
diff --git a/service/src/com/android/car/CarPowerManagementService.java b/service/src/com/android/car/CarPowerManagementService.java
index 41c075e..0bec14c 100644
--- a/service/src/com/android/car/CarPowerManagementService.java
+++ b/service/src/com/android/car/CarPowerManagementService.java
@@ -70,6 +70,8 @@
     private HandlerThread mHandlerThread;
     @GuardedBy("this")
     private PowerHandler mHandler;
+    @GuardedBy("this")
+    private boolean mTimerActive;
     private int mNextWakeupSec = 0;
     private int mTokenValue = 1;
     private boolean mShutdownOnFinish = false;
@@ -312,10 +314,13 @@
 
     @GuardedBy("this")
     private void releaseTimerLocked() {
-        if (mTimer != null) {
-            mTimer.cancel();
+        synchronized (this) {
+            if (mTimer != null) {
+                mTimer.cancel();
+            }
+            mTimer = null;
+            mTimerActive = false;
         }
-        mTimer = null;
     }
 
     private void doHandlePreprocessing() {
@@ -326,6 +331,7 @@
             mProcessingStartTime = SystemClock.elapsedRealtime();
             releaseTimerLocked();
             mTimer = new Timer();
+            mTimerActive = true;
             mTimer.scheduleAtFixedRate(
                     new ShutdownProcessingTimerTask(pollingCount),
                     0 /*delay*/,
@@ -650,16 +656,20 @@
 
         @Override
         public void run() {
-            mCurrentCount++;
-            if (mCurrentCount > mExpirationCount) {
-                PowerHandler handler;
-                synchronized (CarPowerManagementService.this) {
+            synchronized (this) {
+                if (!mTimerActive) {
+                    // Ignore timer expiration since we got cancelled
+                    return;
+                }
+                mCurrentCount++;
+                if (mCurrentCount > mExpirationCount) {
+                    PowerHandler handler;
                     releaseTimerLocked();
                     handler = mHandler;
+                    handler.handleProcessingComplete();
+                } else {
+                    mHal.sendShutdownPostpone(SHUTDOWN_EXTEND_MAX_MS);
                 }
-                handler.handleProcessingComplete();
-            } else {
-                mHal.sendShutdownPostpone(SHUTDOWN_EXTEND_MAX_MS);
             }
         }
     }