SAP: Remove sdp record while BT is being turned off to prevent leak

Remove sdp record created dynamically for SAP server during BT off state.
Without this call, there is leak in sdp layer in stack as sdp record is
never removed, even though the socket is closed.
Also proper checks are added to prevent call to remove sdp record when
adapter is null.

Change-Id: I739cc3115f6cd7fedf9085e8522c96da257e9568
diff --git a/src/com/android/bluetooth/sap/SapService.java b/src/com/android/bluetooth/sap/SapService.java
index 4f7152b..156cca3 100644
--- a/src/com/android/bluetooth/sap/SapService.java
+++ b/src/com/android/bluetooth/sap/SapService.java
@@ -121,7 +121,14 @@
         }
     }
 
-
+    private void removeSdpRecord() {
+        if (mAdapter != null && mSdpHandle >= 0 &&
+                                SdpManager.getDefaultManager() != null) {
+            if(VERBOSE) Log.d(TAG, "Removing SDP record handle: " + mSdpHandle);
+            boolean status = SdpManager.getDefaultManager().removeSdpRecord(mSdpHandle);
+            mSdpHandle = -1;
+        }
+    }
 
     private void startRfcommSocketListener() {
         if (VERBOSE) Log.v(TAG, "Sap Service startRfcommSocketListener");
@@ -148,10 +155,7 @@
                 //       for multiple connections.
                 mServerSocket = mAdapter.listenUsingRfcommOn(
                         BluetoothAdapter.SOCKET_CHANNEL_AUTO_STATIC_NO_SDP, true, true);
-                if (mSdpHandle >= 0) {
-                    SdpManager.getDefaultManager().removeSdpRecord(mSdpHandle);
-                    if (VERBOSE) Log.d(TAG, "Removing SDP record");
-                }
+                removeSdpRecord();
                 mSdpHandle = SdpManager.getDefaultManager().createSapsRecord(SDP_SAP_SERVICE_NAME,
                         mServerSocket.getChannel(), SDP_SAP_VERSION);
             } catch (IOException e) {
@@ -656,6 +660,7 @@
             mIsWaitingAuthorization = false;
             cancelUserTimeoutAlarm();
         }
+        removeSdpRecord();
         mSessionStatusHandler.removeCallbacksAndMessages(null);
         // Request release of all resources
         mSessionStatusHandler.obtainMessage(SHUTDOWN).sendToTarget();