Nfc enable and disable API synchronized.

Fix for NFC service died observed during NFC off/on with SPI open
Transaction close in loop.
diff --git a/src/com/android/nfc/NfcService.java b/src/com/android/nfc/NfcService.java
index cd416b0..a602a2c 100755
--- a/src/com/android/nfc/NfcService.java
+++ b/src/com/android/nfc/NfcService.java
@@ -311,6 +311,12 @@
     // Timeout to re-apply routing if a tag was present and we postponed it
     private static final int APPLY_ROUTING_RETRY_TIMEOUT_MS = 5000;
 
+    // these states are for making enable and disable nfc atomic
+    private int NXP_NFC_STATE_OFF = 0;
+    private int NXP_NFC_STATE_TURNING_ON = 1;
+    private int NXP_NFC_STATE_ON = 2;
+    private int NXP_NFC_STATE_TURNING_OFF = 3;
+
     // eSE handle
     public static final int EE_HANDLE_0xF3 = 0x4C0;
 
@@ -380,6 +386,8 @@
     // and the default AsyncTask thread so it is read unprotected from that
     // thread
     int mState;  // one of NfcAdapter.STATE_ON, STATE_TURNING_ON, etc
+    int mNxpNfcState = NXP_NFC_STATE_OFF;
+
     // fields below are final after onCreate()
     Context mContext;
     private DeviceHost mDeviceHost;
@@ -1008,6 +1016,9 @@
             commitRouting();
             /* WiredSe Init after ESE is discovered and initialised */
             initWiredSe();
+            synchronized (NfcService.this) {
+                mNxpNfcState = NXP_NFC_STATE_ON;
+            }
             return true;
         }
 
@@ -1055,6 +1066,7 @@
             synchronized (NfcService.this) {
                 mCurrentDiscoveryParameters = NfcDiscoveryParameters.getNfcOffParameters();
                 updateState(NfcAdapter.STATE_OFF);
+                mNxpNfcState = NXP_NFC_STATE_OFF;
             }
             releaseSoundPool();
             return result;
@@ -1139,6 +1151,14 @@
     final class NfcAdapterService extends INfcAdapter.Stub {
         @Override
         public boolean enable() throws RemoteException {
+            synchronized (NfcService.this) {
+                if (mNxpNfcState != NXP_NFC_STATE_OFF) {
+                    Log.e(TAG, "mNxpNfcStateis not equal to NXP_NFC_STATE_OFF."
+                                + " Enable NFC Rejected.");
+                    return false;
+                }
+                mNxpNfcState = NXP_NFC_STATE_TURNING_ON;
+            }
             NfcPermissions.enforceAdminPermissions(mContext);
 
             saveNfcOnSetting(true);
@@ -1158,6 +1178,14 @@
        }
         @Override
         public boolean disable(boolean saveState) throws RemoteException {
+          synchronized (NfcService.this) {
+            if (mNxpNfcState != NXP_NFC_STATE_ON) {
+              Log.e(TAG, "mNxpNfcStateis not equal to NXP_NFC_STATE_ON."
+                + " Disable NFC Rejected.");
+              return false;
+            }
+            mNxpNfcState = NXP_NFC_STATE_TURNING_OFF;
+          }
           NfcPermissions.enforceAdminPermissions(mContext);
 
           if (saveState) {