Keep the death recipient alive

Binder doesn't hold on to the death recipient.
This caused audio server to miss notifications about system server
death.

Fixes: 153080001
Test: Manual verification of killing the system process.
Change-Id: Iad1b2d4c5348d3d9917efc6838e86b736fa33094
diff --git a/services/audiopolicy/service/CaptureStateNotifier.cpp b/services/audiopolicy/service/CaptureStateNotifier.cpp
index 8a18efa..135e0a2 100644
--- a/services/audiopolicy/service/CaptureStateNotifier.cpp
+++ b/services/audiopolicy/service/CaptureStateNotifier.cpp
@@ -1,7 +1,7 @@
-#include "CaptureStateNotifier.h"
-
 #define LOG_TAG "CaptureStateNotifier"
 
+#include "CaptureStateNotifier.h"
+
 #include <android/media/ICaptureStateListener.h>
 #include <binder/IBinder.h>
 #include <utils/Log.h>
@@ -22,9 +22,9 @@
     CaptureStateNotifier* const mNotifier;
 };
 
-CaptureStateNotifier::CaptureStateNotifier(bool initialActive) {
-    mActive = initialActive;
-}
+CaptureStateNotifier::CaptureStateNotifier(bool initialActive)
+    : mDeathRecipient(new DeathRecipient(this)), mActive(
+    initialActive) {}
 
 CaptureStateNotifier::~CaptureStateNotifier() {
     LOG_ALWAYS_FATAL_IF(mListener != nullptr);
@@ -33,11 +33,20 @@
 bool CaptureStateNotifier::RegisterListener(const sp<ICaptureStateListener>& listener) {
     std::lock_guard<std::mutex> _l(mMutex);
     LOG_ALWAYS_FATAL_IF(mListener != nullptr);
+    LOG_ALWAYS_FATAL_IF(listener == nullptr);
 
     ALOGI("Registering a listener");
-    mListener = listener;
-    sp<IBinder> binder = IInterface::asBinder(mListener);
-    binder->linkToDeath(new DeathRecipient(this));
+    sp<IBinder> binder = IInterface::asBinder(listener);
+    if (binder != nullptr) {
+        status_t status = binder->linkToDeath(mDeathRecipient);
+        if (status == NO_ERROR) {
+            mListener = listener;
+        } else {
+            ALOGE("Failed to register death listener: %u", status);
+        }
+    } else {
+        ALOGE("Listener failed to cast to a binder.");
+    }
     return mActive;
 }