Android NFC 流程

Posted by Vector Blog on March 15, 2018

先来看 NativeNfcManager :

public class NativeNfcManager implements DeviceHost {

    // 先加载 JNI library
    static {
        System.loadLibrary("nqnfc_nci_jni");
    }

JNI 部分代码在 /vendor/nxp/opensource/packages/apps/Nfc/nci/jni

// 主要是映射 native 方法
jint JNI_OnLoad (JavaVM* jvm, void*)
{
    ALOGV("%s: enter", __func__);
    JNIEnv *e = NULL;

    ALOGI("NFC Service: loading nci JNI");

    // 这里还调用了 PowerSwitch 的 initialize 
    if (android::register_com_android_nfc_NativeNfcManager (e) == -1)
        return JNI_ERR;
    ......
    if (android::register_com_android_nfc_NativeLlcpServiceSocket (e) == -1)
        return JNI_ERR;

    ALOGV("%s: exit", __func__);
    return JNI_VERSION_1_6;
}

enable

    final class NfcAdapterService extends INfcAdapter.Stub {
        @Override
        public boolean enable() throws RemoteException {
	    //保存当前设定的状态值
            saveNfcOnSetting(true);
            new EnableDisableTask().execute(TASK_ENABLE);
            return true;
        }
        boolean enableInternal() {
            if (mState == NfcAdapter.STATE_ON) {
                return true;
            }
            //这里回发送 NfcAdapter.ACTION_ADAPTER_STATE_CHANGED 广播 , 通知状态变化 turning on 
            updateState(NfcAdapter.STATE_TURNING_ON);
            
            // 设定 timeout watch dog
            WatchDogThread watchDog = new WatchDogThread("enableInternal", timeout);
            watchDog.start();
            
            try {
                mRoutingWakeLock.acquire();
                try {
                    if (!mDeviceHost.initialize()) {
                        Log.w(TAG, "Error enabling NFC");
                        updateState(NfcAdapter.STATE_OFF);
                        return false;
                    }
                } finally {
                    mRoutingWakeLock.release();
                }
            } finally {
                watchDog.cancel();
            }
            
            ......

            synchronized (NfcService.this) {
                mObjectMap.clear();
                mP2pLinkManager.enableDisable(mIsNdefPushEnabled, true);
                updateState(NfcAdapter.STATE_ON);
            }
            ......
            return true;
        }

主要工作都是在 NativeNfcManager 的 initialize() , 该方法直接call 到 JNI 中的 nfcManager_doInitialize ()