Disable sensors when an app goes to background

Bug: 74395023
Test: 1) Enable sensor on SensorLogger
      2) Put app to background and wait; verify sensor gets disabled.
      3) Put app to foreground and wait; verify sensor gets re-enabled.
Change-Id: Icf6ab253fad4133431c86bb9a49275f9190ad2e8
diff --git a/services/sensorservice/SensorEventConnection.h b/services/sensorservice/SensorEventConnection.h
index 1ca35c0..3ba5c07 100644
--- a/services/sensorservice/SensorEventConnection.h
+++ b/services/sensorservice/SensorEventConnection.h
@@ -57,7 +57,8 @@
     bool hasSensor(int32_t handle) const;
     bool hasAnySensor() const;
     bool hasOneShotSensors() const;
-    bool addSensor(int32_t handle);
+    bool addSensor(
+        int32_t handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags);
     bool removeSensor(int32_t handle);
     std::vector<int32_t> getActiveSensorHandles() const;
     void setFirstFlushPending(int32_t handle, bool value);
@@ -70,7 +71,7 @@
     uid_t getUid() const { return mUid; }
 
     void setSensorAccess(const bool hasAccess);
-
+    void updateSensorSubscriptions();
 private:
     virtual ~SensorEventConnection();
     virtual void onFirstRef();
@@ -136,13 +137,16 @@
     // privacy not being enabled.
     bool hasSensorAccess();
 
+    void stopAll();
+    void recoverAll();
+
     // Call noteOp for the sensor if the sensor requires a permission
     bool noteOpIfRequired(const sensors_event_t& event);
 
     sp<SensorService> const mService;
     sp<BitTube> mChannel;
     uid_t mUid;
-    mutable Mutex mConnectionLock;
+    mutable std::recursive_mutex mConnectionLock;
     // Number of events from wake up sensors which are still pending and haven't been delivered to
     // the corresponding application. It is incremented by one unit for each write to the socket.
     uint32_t mWakeLockRefCount;
@@ -169,8 +173,17 @@
 
         FlushInfo() : mPendingFlushEventsToSend(0), mFirstFlushPending(false) {}
     };
+
+    struct SensorRequest {
+      nsecs_t samplingPeriodNs;
+      nsecs_t maxBatchReportLatencyNs;
+      int reservedFlags;
+      FlushInfo flushInfo;
+    };
+
     // protected by SensorService::mLock. Key for this map is the sensor handle.
-    std::unordered_map<int32_t, FlushInfo> mSensorInfo;
+    std::unordered_map<int32_t, SensorRequest> mSensorInfo;
+    std::unordered_map<int32_t, SensorRequest> mSensorInfoBackup;
 
     sensors_event_t *mEventCache;
     int mCacheSize, mMaxCacheSize;
@@ -185,7 +198,7 @@
 
     mutable Mutex mDestroyLock;
     bool mDestroyed;
-    bool mHasSensorAccess;
+    std::atomic_bool mHasSensorAccess;
 
     // Store a mapping of sensor handles to required AppOp for a sensor. This map only contains a
     // valid mapping for sensors that require a permission in order to reduce the lookup time.