NFC启动及标签发现流程介绍_nfc tagmo use process-程序员宅基地

技术标签: android  系统  

一、启动流程

1.NfcApplication启动

在这里插入图片描述

NFC应在启动时会检查是否开了nfc_any的feature,并且还检查是否在主用户和主进程,符合这些条件才初始化NFcService,注意这里NfcService并不是一个服务

2. NfcService.java

public NfcService(Application nfcApplication) {
    
        mUserId = ActivityManager.getCurrentUser();
        mContext = nfcApplication;
        mNfcTagService = new TagService();  // 初始化NfcTag 供上层接口
        mNfcAdapter = new NfcAdapterService();  // 初始化NfcAdapter供上层接口
        mRoutingTableParser = new RoutingTableParser();
        Log.i(TAG, "Starting NFC service");
        sService = this;
        mScreenStateHelper = new ScreenStateHelper(mContext);   // 屏幕状态应该是和亮灭屏状态相关
        mContentResolver = mContext.getContentResolver();
        mDeviceHost = new NativeNfcManager(mContext, this);   // 底层nfc核心类
        mNfcUnlockManager = NfcUnlockManager.getInstance();   // 解锁锁屏相关
        mHandoverDataParser = new HandoverDataParser();
        boolean isNfcProvisioningEnabled = false;
        try {
    
			// 是否让nfc 在开机向导节点使能
            isNfcProvisioningEnabled = mContext.getResources().getBoolean(
                    R.bool.enable_nfc_provisioning);
        } catch (NotFoundException e) {
    
        }
        if (isNfcProvisioningEnabled) {
    
			// 获取开机向导状态
            mInProvisionMode = Settings.Global.getInt(mContentResolver,
                    Settings.Global.DEVICE_PROVISIONED, 0) == 0;
        } else {
    
            mInProvisionMode = false;
        }
        mNfcDispatcher = new NfcDispatcher(mContext, mHandoverDataParser, mInProvisionMode);  // nfc的事件分发
        mPrefs = mContext.getSharedPreferences(PREF, Context.MODE_PRIVATE);
        mPrefsEditor = mPrefs.edit();
        mState = NfcAdapter.STATE_OFF;
        mAlwaysOnState = NfcAdapter.STATE_OFF;
        mIsDebugBuild = "userdebug".equals(Build.TYPE) || "eng".equals(Build.TYPE);   // 系统编译版本,应该是会在user和debug版本做一些区别
        mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);  // 电源相关可以控制亮灭屏
        mRoutingWakeLock = mPowerManager.newWakeLock(
                PowerManager.PARTIAL_WAKE_LOCK, "NfcService:mRoutingWakeLock");
        mRequireUnlockWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                        | PowerManager.ACQUIRE_CAUSES_WAKEUP
                        | PowerManager.ON_AFTER_RELEASE, "NfcService:mRequireUnlockWakeLock");
        mKeyguard = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);  // 锁屏解锁
        mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE); // 用户管理
        mVibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE); // 振动服务
        mVibrationEffect = VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE);
        mScreenState = mScreenStateHelper.checkScreenState();
        mNumTagsDetected = new AtomicInteger();  // 发现标签个数
        mNumP2pDetected = new AtomicInteger();   // 发现点对点个数
        mNumHceDetected = new AtomicInteger();   // 发现模拟卡个数
        mBackupManager = new BackupManager(mContext);
        // Intents for all users
        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        filter.addAction(Intent.ACTION_USER_SWITCHED);
        filter.addAction(Intent.ACTION_USER_ADDED);
        mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, null); // 监测亮灭屏状态,用户添加、切换、就绪状态
        // Listen for work profile adds or removes.
        IntentFilter managedProfileFilter = new IntentFilter();
        managedProfileFilter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
        managedProfileFilter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED);
        managedProfileFilter.addAction(Intent.ACTION_MANAGED_PROFILE_AVAILABLE);
        managedProfileFilter.addAction(Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE);
        mContext.registerReceiverAsUser(mManagedProfileReceiver, UserHandle.ALL,
                managedProfileFilter, null, null);  // 这里监听manger profile相关状态
        IntentFilter ownerFilter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
        ownerFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
        ownerFilter.addAction(Intent.ACTION_SHUTDOWN);
        mContext.registerReceiverAsUser(mOwnerReceiver, UserHandle.ALL, ownerFilter, null, null); //监听关机、外部存储卸载、挂载状态
        ownerFilter = new IntentFilter();
        ownerFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
        ownerFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        ownerFilter.addDataScheme("package");
        mContext.registerReceiverAsUser(mOwnerReceiver, UserHandle.ALL, ownerFilter, null, null); // 监听应用安装、移除事件
        IntentFilter policyFilter = new IntentFilter(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
        mContext.registerReceiverAsUser(mPolicyReceiver, UserHandle.ALL, policyFilter, null, null); //监听设备策略状态改变事件
        updatePackageCache();
        PackageManager pm = mContext.getPackageManager();
        mIsBeamCapable = pm.hasSystemFeature(PackageManager.FEATURE_NFC_BEAM); //检查是否支持android beam
        mIsNdefPushEnabled =
            mPrefs.getBoolean(PREF_NDEF_PUSH_ON, NDEF_PUSH_ON_DEFAULT) &&
            mIsBeamCapable;
        if (mIsBeamCapable) {
    
            mP2pLinkManager = new P2pLinkManager(
                mContext, mHandoverDataParser, mDeviceHost.getDefaultLlcpMiu(),
                mDeviceHost.getDefaultLlcpRwSize());
        }
        enforceBeamShareActivityPolicy(mContext, new UserHandle(mUserId));
        mIsHceCapable =
                pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION) ||
                pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION_NFCF); // 检查是否支持卡模拟
        mIsHceFCapable =
                pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION_NFCF);
        if (mIsHceCapable) {
    
            mCardEmulationManager = new CardEmulationManager(mContext);
        }
        mForegroundUtils = ForegroundUtils.getInstance();
        mIsSecureNfcCapable = mNfcAdapter.deviceSupportsNfcSecure();
        mIsSecureNfcEnabled =
            mPrefs.getBoolean(PREF_SECURE_NFC_ON, SECURE_NFC_ON_DEFAULT) &&
            mIsSecureNfcCapable;
        mDeviceHost.setNfcSecure(mIsSecureNfcEnabled);
        sToast_debounce_time_ms =
                mContext.getResources().getInteger(R.integer.toast_debounce_time_ms);
        if(sToast_debounce_time_ms > MAX_TOAST_DEBOUNCE_TIME) {
    
            sToast_debounce_time_ms = MAX_TOAST_DEBOUNCE_TIME;
        }
        // Notification message variables
        mDispatchFailedCount = 0;
        if (mContext.getResources().getBoolean(R.bool.enable_antenna_blocked_alert) &&
            !mPrefs.getBoolean(PREF_ANTENNA_BLOCKED_MESSAGE_SHOWN, ANTENNA_BLOCKED_MESSAGE_SHOWN_DEFAULT)) {
    
            mAntennaBlockedMessageShown = false;
            mDispatchFailedMax =
                mContext.getResources().getInteger(R.integer.max_antenna_blocked_failure_count);
        } else {
    
            mAntennaBlockedMessageShown = true;
        }
        // Polling delay variables
        mPollDelay = mContext.getResources().getInteger(R.integer.unknown_tag_polling_delay);
        mNotifyDispatchFailed = mContext.getResources().getBoolean(R.bool.enable_notify_dispatch_failed);
        mNotifyReadFailed = mContext.getResources().getBoolean(R.bool.enable_notify_read_failed);
        mPollingDisableAllowed = mContext.getResources().getBoolean(R.bool.polling_disable_allowed); // 一些静态配置
        // Make sure this is only called when object construction is complete.
        ServiceManager.addService(SERVICE_NAME, mNfcAdapter);
        mIsAlwaysOnSupported =
            mContext.getResources().getBoolean(R.bool.nfcc_always_on_allowed);
        new EnableDisableTask().execute(TASK_BOOT);  // do blocking boot tasks
        mHandler.sendEmptyMessageDelayed(MSG_UPDATE_STATS, STATS_UPDATE_INTERVAL_MS);
        IVrManager mVrManager = IVrManager.Stub.asInterface(ServiceManager.getService(
                mContext.VR_SERVICE));
        if (mVrManager != null) {
    
            try {
    
                mVrManager.registerListener(mVrStateCallbacks);
                mIsVrModeEnabled = mVrManager.getVrModeState();
            } catch (RemoteException e) {
    
                Log.e(TAG, "Failed to register VR mode state listener: " + e);
            }
        }
        mSEService = ISecureElementService.Stub.asInterface(ServiceManager.getService(
                Context.SECURE_ELEMENT_SERVICE));
    }

然后是NativeNfcManager.java的初始化,它会顺带把jni一起初始化,jni中会将java中的代码函数句柄获取到:

3. NativeNfcManager.java

initializeNativeStructure - >NativeNfcManager:nfcManager_initNativeStruc

static jboolean nfcManager_initNativeStruc(JNIEnv* e, jobject o) {
     
  initializeGlobalDebugEnabledFlag();
  initializeMfcReaderOption();
  initializeRecoveryOption();
  initializeNfceePowerAndLinkConf();
  DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s: enter", __func__);

  nfc_jni_native_data* nat =
      (nfc_jni_native_data*)malloc(sizeof(struct nfc_jni_native_data));
  if (nat == NULL) {
    
    LOG(ERROR) << StringPrintf("%s: fail allocate native data", __func__);
return JNI_FALSE;
  }

  memset(nat, 0, sizeof(*nat));
  e->GetJavaVM(&(nat->vm));
  nat->env_version = e->GetVersion();
  nat->manager = e->NewGlobalRef(o);
ScopedLocalRef<jclass> cls(e, e->GetObjectClass(o));
  jfieldID f = e->GetFieldID(cls.get(), "mNative", "J");
  e->SetLongField(o, f, (jlong)nat);

  /* Initialize native cached references */
  gCachedNfcManagerNotifyNdefMessageListeners =
      e->GetMethodID(cls.get(), "notifyNdefMessageListeners",
                     "(Lcom/android/nfc/dhimpl/NativeNfcTag;)V");
  gCachedNfcManagerNotifyLlcpLinkActivation =
      e->GetMethodID(cls.get(), "notifyLlcpLinkActivation",
                     "(Lcom/android/nfc/dhimpl/NativeP2pDevice;)V");
  gCachedNfcManagerNotifyLlcpLinkDeactivated =
      e->GetMethodID(cls.get(), "notifyLlcpLinkDeactivated",
                     "(Lcom/android/nfc/dhimpl/NativeP2pDevice;)V");

gCachedNfcManagerNotifyLlcpFirstPacketReceived =
      e->GetMethodID(cls.get(), "notifyLlcpLinkFirstPacketReceived",
                     "(Lcom/android/nfc/dhimpl/NativeP2pDevice;)V");

  gCachedNfcManagerNotifyHostEmuActivated =
      e->GetMethodID(cls.get(), "notifyHostEmuActivated", "(I)V");
  gCachedNfcManagerNotifyHostEmuData =
      e->GetMethodID(cls.get(), "notifyHostEmuData", "(I[B)V");

  gCachedNfcManagerNotifyHostEmuDeactivated =
      e->GetMethodID(cls.get(), "notifyHostEmuDeactivated", "(I)V");

gCachedNfcManagerNotifyRfFieldActivated =
      e->GetMethodID(cls.get(), "notifyRfFieldActivated", "()V");
  gCachedNfcManagerNotifyRfFieldDeactivated =
      e->GetMethodID(cls.get(), "notifyRfFieldDeactivated", "()V");

gCachedNfcManagerNotifyTransactionListeners = e->GetMethodID(
      cls.get(), "notifyTransactionListeners", "([B[BLjava/lang/String;)V");

  gCachedNfcManagerNotifyEeUpdated =
      e->GetMethodID(cls.get(), "notifyEeUpdated", "()V");

gCachedNfcManagerNotifyHwErrorReported =
      e->GetMethodID(cls.get(), "notifyHwErrorReported", "()V");

  if (nfc_jni_cache_object(e, gNativeNfcTagClassName, &(nat->cached_NfcTag)) ==
      -1) {
    
    LOG(ERROR) << StringPrintf("%s: fail cache NativeNfcTag", __func__);
    return JNI_FALSE;
  }
  if (nfc_jni_cache_object(e, gNativeP2pDeviceClassName,
                           &(nat->cached_P2pDevice)) == -1) {
    
    LOG(ERROR) << StringPrintf("%s: fail cache NativeP2pDevice", __func__);
    return JNI_FALSE;
  }

  DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s: exit", __func__);
  return JNI_TRUE;
}

其中gCachedNfcManagerNotifyNdefMessageListeners 这个函数在后续标签会用到

4. NativeNfcManager.cpp

一个重要的函数nfcManager_doInitialize,会在NfcService初始化的时候被调用在EnableDisableTask中。具体不详说,直接看nfcManager_doInitialize

static jboolean nfcManager_doInitialize(JNIEnv* e, jobject o) {
     
#if (NXP_EXTNS == TRUE)
  tNFA_MW_VERSION mwVer;
#endif
  initializeGlobalDebugEnabledFlag(); // 初始化debug信息。开log可以在这里
  tNFA_STATUS stat = NFA_STATUS_OK;
  sIsRecovering = false;

  PowerSwitch& powerSwitch = PowerSwitch::getInstance();

  if (sIsNfaEnabled) {
    
    DLOG_IF(INFO, nfc_debug_enabled)
        << StringPrintf("%s: already enabled", __func__);
    goto TheEnd;
  }
#if (NXP_EXTNS == TRUE)
    mwVer=  NFA_GetMwVersion();  // 获取nfc版本号
    DLOG_IF(INFO, true) << StringPrintf(
        "%s:  MW Version: NFC_AR_INFRA_%04X_%02d.%02x.%02x", __func__,
        mwVer.validation, mwVer.android_version,
        mwVer.major_version, mwVer.minor_version);
#endif

  powerSwitch.initialize(PowerSwitch::FULL_POWER); //根据状态是否给nfc上电

  {
    

    NfcAdaptation& theInstance = NfcAdaptation::GetInstance();
    theInstance.Initialize();  // start GKI, NCI task, NFC task
    {
        
      SyncEventGuard guard(sNfaEnableEvent);
      tHAL_NFC_ENTRY* halFuncEntries = theInstance.GetHalEntryFuncs();

      NFA_Init(halFuncEntries);

      stat = NFA_Enable(nfaDeviceManagementCallback, nfaConnectionCallback); // 使能nfc模块,并注册管理回调和连接回调,nfaConnectionCallback在发现设备时会被调用
      if (stat == NFA_STATUS_OK) {
    
        sNfaEnableEvent.wait();  // wait for NFA command to finish
      }    
      EXTNS_Init(nfaDeviceManagementCallback, nfaConnectionCallback);
    }
    if (stat == NFA_STATUS_OK) {
    
      // sIsNfaEnabled indicates whether stack started successfully
      if (sIsNfaEnabled) {
     // 这里下面对一系列模块进行初始化
        sRoutingInitialized =
            RoutingManager::getInstance().initialize(getNative(e, o));
        nativeNfcTag_registerNdefTypeHandler();
        NfcTag::getInstance().initialize(getNative(e, o));
        PeerToPeer::getInstance().initialize();
        PeerToPeer::getInstance().handleNfcOnOff(true);
        HciEventManager::getInstance().initialize(getNative(e, o));
    /
        // Add extra configuration here (work-arounds, etc.)

        if (gIsDtaEnabled == true) {
     //设置一些配置
          uint8_t configData = 0;
          configData = 0x01; /* Poll NFC-DEP : Highest Available Bit Rates */
          NFA_SetConfig(NCI_PARAM_ID_BITR_NFC_DEP, sizeof(uint8_t),
                        &configData);
          configData = 0x0B; /* Listen NFC-DEP : Waiting Time */
          NFA_SetConfig(NCI_PARAM_ID_NFC_DEP_OP, sizeof(uint8_t), &configData);
        }

        struct nfc_jni_native_data* nat = getNative(e, o);
        if (nat) {
    
          nat->tech_mask =
              NfcConfig::getUnsigned(NAME_POLLING_TECH_MASK, DEFAULT_TECH_MASK);
          DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf(
              "%s: tag polling tech mask=0x%X", __func__, nat->tech_mask);
        }
    // if this value exists, set polling interval.
        nat->discovery_duration = NfcConfig::getUnsigned(
            NAME_NFA_DM_DISC_DURATION_POLL, DEFAULT_DISCOVERY_DURATION);

        NFA_SetRfDiscoveryDuration(nat->discovery_duration);

        // get LF_T3T_MAX
        {
    
          SyncEventGuard guard(gNfaGetConfigEvent);
tNFA_PMID configParam[1] = {
    NCI_PARAM_ID_LF_T3T_MAX};
          stat = NFA_GetConfig(1, configParam);
          if (stat == NFA_STATUS_OK) {
    
            gNfaGetConfigEvent.wait();
            if (gCurrentConfigLen >= 4 ||
                gConfig[1] == NCI_PARAM_ID_LF_T3T_MAX) {
    
              DLOG_IF(INFO, nfc_debug_enabled)
                  << StringPrintf("%s: lfT3tMax=%d", __func__, gConfig[3]);
              sLfT3tMax = gConfig[3];
            }
          }
    }

        prevScreenState = NFA_SCREEN_STATE_OFF_LOCKED;

        // Do custom NFCA startup configuration.
        doStartupConfig();
#ifdef DTA_ENABLED
        NfcDta::getInstance().setNfccConfigParams();
#endif /* DTA_ENABLED */
        goto TheEnd;
      }
    }
    LOG(ERROR) << StringPrintf("%s: fail nfa enable; error=0x%X", __func__,
                               stat);

    if (sIsNfaEnabled) {
    
      EXTNS_Close();
      stat = NFA_Disable(FALSE /* ungraceful */);
    }

    theInstance.Finalize();
  }

TheEnd: // 初始化成功之后进入低电量待机
  if (sIsNfaEnabled)
    PowerSwitch::getInstance().setLevel(PowerSwitch::LOW_POWER);
  DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s: exit", __func__);
  return sIsNfaEnabled ? JNI_TRUE : JNI_FALSE;
}

二、标签发现流程

当有标签靠近时,底层会促发nfaConnectionCallback给一个NFA_ACTIVATED_EVT的事件过来,当然这个过程中不仅仅会发生这一个事件。NativeNfcManger在收到这个事件之后

......
case NFA_ACTIVATED_EVT:  // NFC link/protocol activated
    {
    
      DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf(
          "%s: NFA_ACTIVATED_EVT: gIsSelectingRfInterface=%d, sIsDisabling=%d",
          __func__, gIsSelectingRfInterface, sIsDisabling);
      uint8_t activatedProtocol =
          (tNFA_INTF_TYPE)eventData->activated.activate_ntf.protocol; // 获取nfc协议
    if (NFC_PROTOCOL_T5T == activatedProtocol &&
          NfcTag::getInstance().getNumDiscNtf()) {
     // 判断是不是t5t
        /* T5T doesn't support multiproto detection logic */
        NfcTag::getInstance().setNumDiscNtf(0);
      }
      if ((eventData->activated.activate_ntf.protocol !=
           NFA_PROTOCOL_NFC_DEP) &&
          (!isListenMode(eventData->activated))) {
     // 判断是不是dep
        nativeNfcTag_setRfInterface(
            (tNFA_INTF_TYPE)eventData->activated.activate_ntf.intf_param.type);
        nativeNfcTag_setActivatedRfProtocol(activatedProtocol);
      }
      if (EXTNS_GetConnectFlag() == TRUE) {
     //判断有没有外部服务连接,有就使能它
        NfcTag::getInstance().setActivationState();
        nativeNfcTag_doConnectStatus(true);
        break;
      }
    NfcTag::getInstance().setActive(true);  // nfc tag 激活
      if (sIsDisabling || !sIsNfaEnabled) break;
      gActivated = true;

      NfcTag::getInstance().setActivationState(); //修改激活状态
      if (gIsSelectingRfInterface) {
    
        nativeNfcTag_doConnectStatus(true);
        break;
      }
    nativeNfcTag_resetPresenceCheck();
      if (!isListenMode(eventData->activated) &&
          (prevScreenState == NFA_SCREEN_STATE_OFF_LOCKED ||
           prevScreenState == NFA_SCREEN_STATE_OFF_UNLOCKED)) {
    
        NFA_Deactivate(FALSE);
      }
      if (isPeerToPeer(eventData->activated)) {
     // 判断是不是p2p
        if (sReaderModeEnabled) {
    
          DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf(
              "%s: ignoring peer target in reader mode.", __func__);
          NFA_Deactivate(FALSE);
          break;
        }
        sP2pActive = true;
        DLOG_IF(INFO, nfc_debug_enabled)
            << StringPrintf("%s: NFA_ACTIVATED_EVT; is p2p", __func__);
        if (NFC_GetNCIVersion() == NCI_VERSION_1_0) {
    
         // Disable RF field events in case of p2p
          uint8_t nfa_disable_rf_events[] = {
    0x00};
          DLOG_IF(INFO, nfc_debug_enabled)
              << StringPrintf("%s: Disabling RF field events", __func__);
          status = NFA_SetConfig(NCI_PARAM_ID_RF_FIELD_INFO,
                                 sizeof(nfa_disable_rf_events),
                                 &nfa_disable_rf_events[0]);
          if (status == NFA_STATUS_OK) {
    
            DLOG_IF(INFO, nfc_debug_enabled)
                << StringPrintf("%s: Disabled RF field events", __func__);
          } else {
    
            LOG(ERROR) << StringPrintf("%s: Failed to disable RF field events",
                                       __func__);
          }
        }
      } else {
     // 不是P2p 是标签
        NfcTag::getInstance().connectionEventHandler(connEvent, eventData);  //通知nfc tag进行处理
        if (NfcTag::getInstance().getNumDiscNtf()) {
    
          /*If its multiprotocol tag, deactivate tag with current selected
          protocol to sleep . Select tag with next supported protocol after
          deactivation event is received*/
          NFA_Deactivate(true);
        }

        // We know it is not activating for P2P.  If it activated in
        // listen mode then it is likely for an SE transaction.
        // Send the RF Event.
        if (isListenMode(eventData->activated)) {
    
          sSeRfActive = true;
        }
      }
    } break;
void NfcTag::connectionEventHandler(uint8_t event, tNFA_CONN_EVT_DATA* data) {
    
......
case NFA_ACTIVATED_EVT:
      // Only do tag detection if we are polling and it is not 'EE Direct RF'
      // activation (which may happen when we are activated as a tag).
      if (data->activated.activate_ntf.rf_tech_param.mode <
              NCI_DISCOVERY_TYPE_LISTEN_A &&
          data->activated.activate_ntf.intf_param.type !=
              NFC_INTERFACE_EE_DIRECT_RF) {
    
        tNFA_ACTIVATED& activated = data->activated;
      if (IsSameKovio(activated)) break;
        mIsActivated = true;
        mProtocol = activated.activate_ntf.protocol;
        calculateT1tMaxMessageSize(activated); // 计算最大信息大小
        discoverTechnologies(activated); // 激活发现的tech
        createNativeNfcTag(activated); //创建nfc tag
      }
      break;
......
void NfcTag::createNativeNfcTag(tNFA_ACTIVATED& activationData) {
    
  static const char fn[] = "NfcTag::createNativeNfcTag";
  DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s: enter", fn);

  JNIEnv* e = NULL;
  ScopedAttach attach(mNativeData->vm, &e);
  if (e == NULL) {
    
    LOG(ERROR) << StringPrintf("%s: jni env is null", fn);
    return;
  }
  ScopedLocalRef<jclass> tag_cls(e,
                                 e->GetObjectClass(mNativeData->cached_NfcTag));
  if (e->ExceptionCheck()) {
    
    e->ExceptionClear();
    LOG(ERROR) << StringPrintf("%s: failed to get class", fn);
    return;
  }
  // create a new Java NativeNfcTag object
  jmethodID ctor = e->GetMethodID(tag_cls.get(), "<init>", "()V");
  ScopedLocalRef<jobject> tag(e, e->NewObject(tag_cls.get(), ctor)); // 调用NativeNfcTag.java 中的函数创建tag

  // fill NativeNfcTag's mProtocols, mTechList, mTechHandles, mTechLibNfcTypes
  fillNativeNfcTagMembers1(e, tag_cls.get(), tag.get());

  // fill NativeNfcTag's members: mHandle, mConnectedTechnology
  fillNativeNfcTagMembers2(e, tag_cls.get(), tag.get(), activationData);
// fill NativeNfcTag's members: mTechPollBytes
  fillNativeNfcTagMembers3(e, tag_cls.get(), tag.get(), activationData);

  // fill NativeNfcTag's members: mTechActBytes
  fillNativeNfcTagMembers4(e, tag_cls.get(), tag.get(), activationData);

  // fill NativeNfcTag's members: mUid
  fillNativeNfcTagMembers5(e, tag_cls.get(), tag.get(), activationData);
  if (mNativeData->tag != NULL) {
    
    e->DeleteGlobalRef(mNativeData->tag);
  }
  mNativeData->tag = e->NewGlobalRef(tag.get());

  DLOG_IF(INFO, nfc_debug_enabled)
      << StringPrintf("%s; mNumDiscNtf=%x", fn, mNumDiscNtf);
  if (!mNumDiscNtf) {
    
    // notify NFC service about this new tag
    DLOG_IF(INFO, nfc_debug_enabled)
        << StringPrintf("%s: try notify nfc service", fn);
    e->CallVoidMethod(mNativeData->manager,
                      android::gCachedNfcManagerNotifyNdefMessageListeners,
                      tag.get()); // 回调到NativeNfcManager中,回到java层
   if (e->ExceptionCheck()) {
    
      e->ExceptionClear();
      LOG(ERROR) << StringPrintf("%s: fail notify nfc service", fn);
    }
    deleteglobaldata(e);
  } else {
    
    DLOG_IF(INFO, nfc_debug_enabled)
        << StringPrintf("%s: Selecting next tag", fn);
  }

  DLOG_IF(INFO, nfc_debug_enabled) << StringPrintf("%s: exit", fn);
}

接着就到了NativeNfcManager.java


    /** Notifies Ndef Message (TODO: rename into notifyTargetDiscovered) */
    private void notifyNdefMessageListeners(NativeNfcTag tag) {
    
        mListener.onRemoteEndpointDiscovered(tag);
    }   

然后回调到NfcService.java

    @Override
    public void onRemoteEndpointDiscovered(TagEndpoint tag) {
    
        sendMessage(NfcService.MSG_NDEF_TAG, tag);
    }

final class NfcServiceHandler extends Handler {
    
        @Override
        public void handleMessage(Message msg) {
    
......
		case MSG_NDEF_TAG:
		....
		NdefMessage ndefMsg = tag.findAndReadNdef(); // 查找ndf数据,这里会对设备进行重连接,有三次机会,都没连上则nfc前台不会相应
		...
		mLastReadNdefMessage = ndefMsg;

        tag.startPresenceChecking(presenceCheckDelay, callback);
        dispatchTagEndpoint(tag, readerParams); //这里就派发到监听的应用去了
......

三、开启debug信息

Nfc调试开启debug信息 persist.nfc.debug_enabled 设为true

或者libnfc-nci.conf 中把NFC_DEBUG_ENABLED置为1

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/wh2526422/article/details/136944870

智能推荐

Linux查看登录用户日志_怎么记录linux设备 发声的登录和登出-程序员宅基地

文章浏览阅读8.6k次。一、Linux记录用户登录信息文件1  /var/run/utmp----记录当前正在登录系统的用户信息;2  /var/log/wtmp----记录当前正在登录和历史登录系统的用户信息;3  /var/log/btmp:记录失败的登录尝试信息。二、命令用法1.命令last,lastb---show a listing of la_怎么记录linux设备 发声的登录和登出

第四章笔记:遍历--算法学中的万能钥匙-程序员宅基地

文章浏览阅读167次。摘要:1. 简介 2. 公园迷宫漫步 3. 无线迷宫与最短(不加权)路径问题 4. 强连通分量1. 简介在计算机科学裡,树的遍历(也称为树的搜索)是圖的遍歷的一种,指的是按照某种规则,不重复地访问某种樹的所有节点的过程。具体的访问操作可能是检查节点的值、更新节点的值等。不同的遍历方式,其访问节点的顺序是不一样的。两种著名的基本遍历策略:深度优先搜索(DFS) 和 广度优先搜索(B...

【案例分享】使用ActiveReports报表工具,在.NET MVC模式下动态创建报表_activereports.net 实现查询报表功能-程序员宅基地

文章浏览阅读591次。提起报表,大家会觉得即熟悉又陌生,好像常常在工作中使用,又似乎无法准确描述报表。今天我们来一起了解一下什么是报表,报表的结构、构成元素,以及为什么需要报表。什么是报表简单的说:报表就是通过表格、图表等形式来动态显示数据,并为使用者提供浏览、打印、导出和分析的功能,可以用公式表示为:报表 = 多样的布局 + 动态的数据 + 丰富的输出报表通常包含以下组成部分:报表首页:在报表的开..._activereports.net 实现查询报表功能

Ubuntu18.04 + GNOME xrdp + Docker + GUI_docker xrdp ubuntu-程序员宅基地

文章浏览阅读6.6k次。最近实验室需要用Cadence,这个软件的安装非常麻烦,每一次配置都要几个小时,因此打算把Cadence装进Docker。但是Cadence运行时需要GUI,要对Docker进行一些配置。我们实验室的服务器运行的是Ubuntu18.04,默认桌面GNOME,Cadence装进Centos的Docker。安装Ubuntu18.04服务器上安装Ubuntu18.04的教程非常多,在此不赘述了安装..._docker xrdp ubuntu

iOS AVFoundation实现相机功能_ios avcapturestillimageoutput 兼容性 ios17 崩溃-程序员宅基地

文章浏览阅读1.8k次,点赞2次,收藏2次。首先导入头文件#import 导入头文件后创建几个相机必须实现的对象 /** * AVCaptureSession对象来执行输入设备和输出设备之间的数据传递 */ @property (nonatomic, strong) AVCaptureSession* session; /** * 输入设备 */_ios avcapturestillimageoutput 兼容性 ios17 崩溃

Oracle动态性能视图--v$sysstat_oracle v$sysstat视图-程序员宅基地

文章浏览阅读982次。按照OracleDocument中的描述,v$sysstat存储自数据库实例运行那刻起就开始累计全实例(instance-wide)的资源使用情况。 类似于v$sesstat,该视图存储下列的统计信息:1>.事件发生次数的统计(如:user commits)2>._oracle v$sysstat视图

随便推点

Vue router报错:NavigationDuplicated {_name: "NavigationDuplicated", name: "NavigationDuplicated"}的解决方法_navigationduplicated {_name: 'navigationduplicated-程序员宅基地

文章浏览阅读7.6k次,点赞2次,收藏9次。我最近做SPA项目开发动态树的时候一直遇到以下错误:当我点击文章管理需要跳转路径时一直报NavigationDuplicated {_name: “NavigationDuplicated”, name: “NavigationDuplicated”}这个错误但是当我点击文章管理后,路径跳转却是成功的<template> <div> 文章管理页面 <..._navigationduplicated {_name: 'navigationduplicated', name: 'navigationduplic

Webrtc回声消除模式(Aecm)屏蔽舒适噪音(CNG)_webrtc aecm 杂音-程序员宅基地

文章浏览阅读3.9k次。版本VoiceEngine 4.1.0舒适噪音生成(comfort noise generator,CNG)是一个在通话过程中出现短暂静音时用来为电话通信产生背景噪声的程序。#if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS)static const EcModes kDefaultEcMode = kEcAecm;#elsestati..._webrtc aecm 杂音

医学成像原理与图像处理一:概论_医学成像与图像处理技术知识点总结-程序员宅基地

文章浏览阅读6.3k次,点赞9次,收藏19次。医学成像原理与图像处理一:概论引言:本系列博客为医学成像原理与图像处理重要笔记,由于是手写,在此通过扫描录入以图片的形式和电子版增补内容将其进行组织和共享。前半部分内容为图像处理基础内容,包括图像的灰度级处理、空间域滤波、频率域滤波、图像增强和分割等;后半部分内容为医学影象技术,包括常规胶片X光机、CR、DR、CT、DSA等X射线摄影技术、超声成像技术、磁共振成像(MRI)技术等。本篇主要内容是概论。_医学成像与图像处理技术知识点总结

notepad++ v8.5.3 安装插件,安装失败怎么处理?下载进度为0怎么处理?_nodepa++-程序员宅基地

文章浏览阅读591次,点赞13次,收藏10次。notepad++ v8.5.3 安装插件,下载进度为0_nodepa++

hive某个字段中包括\n(和换行符冲突)_hive sql \n-程序员宅基地

文章浏览阅读2.1w次。用spark执行SQL保存到Hive中: hiveContext.sql(&quot;insert overwrite table test select * from aaa&quot;)执行完成,没报错,但是核对结果的时候,发现有几笔数据超出指定范围(实际只包含100/200)最终排查到是ret_pay_remark 字段包含换行符,解决方案:执行SQL中把特殊字符替换掉regexp_replace(..._hive sql \n

印象笔记05:如何打造更美的印象笔记超级笔记_好的印象笔记怎么做的-程序员宅基地

文章浏览阅读520次,点赞10次,收藏8次。印象笔记05:如何打造更美的印象笔记超级笔记本文介绍印象笔记的具体使用,如何打造更美更实用的笔记。首先想要笔记更加好看和实用,我认为要使用超级笔记。所谓超级笔记就是具有很多便捷功能的笔记。_好的印象笔记怎么做的

推荐文章

热门文章

相关标签