一、启动流程
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