Merge "Cleanup handle when remote is dead" into oc-dev
diff --git a/sensorservice/libsensorndkbridge/ASensorManager.cpp b/sensorservice/libsensorndkbridge/ASensorManager.cpp
index bd01f13..821ed20 100644
--- a/sensorservice/libsensorndkbridge/ASensorManager.cpp
+++ b/sensorservice/libsensorndkbridge/ASensorManager.cpp
@@ -30,6 +30,7 @@
 using android::frameworks::sensorservice::V1_0::Result;
 using android::hardware::sensors::V1_0::SensorType;
 using android::sp;
+using android::wp;
 using android::Mutex;
 using android::status_t;
 using android::OK;
@@ -56,11 +57,29 @@
     return sInstance;
 }
 
+void ASensorManager::SensorDeathRecipient::serviceDied(
+        uint64_t, const wp<::android::hidl::base::V1_0::IBase>&) {
+    LOG(ERROR) << "Sensor service died. Cleanup sensor manager instance!";
+    Mutex::Autolock autoLock(gLock);
+    delete sInstance;
+    sInstance = NULL;
+}
+
 ASensorManager::ASensorManager()
     : mInitCheck(NO_INIT) {
     mManager = ISensorManager::getService();
     if (mManager != NULL) {
-        mInitCheck = OK;
+        mDeathRecipient = new SensorDeathRecipient();
+        Return<bool> linked = mManager->linkToDeath(mDeathRecipient, /*cookie*/ 0);
+        if (!linked.isOk()) {
+            LOG(ERROR) << "Transaction error in linking to sensor service death: " <<
+                    linked.description().c_str();
+        } else if (!linked) {
+            LOG(WARNING) << "Unable to link to sensor service death notifications";
+        } else {
+            LOG(DEBUG) << "Link to sensor service death notification successful";
+            mInitCheck = OK;
+        }
     }
 }
 
diff --git a/sensorservice/libsensorndkbridge/ASensorManager.h b/sensorservice/libsensorndkbridge/ASensorManager.h
index 04ea032..1a07706 100644
--- a/sensorservice/libsensorndkbridge/ASensorManager.h
+++ b/sensorservice/libsensorndkbridge/ASensorManager.h
@@ -46,10 +46,19 @@
     void destroyEventQueue(ASensorEventQueue *queue);
 
 private:
+
+    struct SensorDeathRecipient : public android::hardware::hidl_death_recipient
+    {
+        // hidl_death_recipient interface
+        virtual void serviceDied(uint64_t cookie,
+                const ::android::wp<::android::hidl::base::V1_0::IBase>& who) override;
+    };
+
     using ISensorManager = android::frameworks::sensorservice::V1_0::ISensorManager;
     using SensorInfo = android::hardware::sensors::V1_0::SensorInfo;
 
     static ASensorManager *sInstance;
+    android::sp<SensorDeathRecipient> mDeathRecipient = nullptr;
 
     android::status_t mInitCheck;
     android::sp<ISensorManager> mManager;