NFC应在启动时会检查是否开了nfc_any的feature,并且还检查是否在主用户和主进程,符合这些条件才初始化NFcService,注意这里NfcService并不是一个服务
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中的代码函数句柄获取到:
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 这个函数在后续标签会用到
一个重要的函数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); //这里就派发到监听的应用去了
......
Nfc调试开启debug信息 persist.nfc.debug_enabled 设为true
或者libnfc-nci.conf 中把NFC_DEBUG_ENABLED置为1
文章浏览阅读1.2k次,点赞35次,收藏18次。AutowiredPostConstruct 注释用于在依赖关系注入完成之后需要执行的方法上,以执行任何初始化。此方法必须在将类放入服务之前调用。支持依赖关系注入的所有类都必须支持此注释。即使类没有请求注入任何资源,用 PostConstruct 注释的方法也必须被调用。只有一个方法可以用此注释进行注释。_springboot2.7获取bean
文章浏览阅读2.1k次。理论介绍 节点定义package logistic;public class Instance { public int label; public double[] x; public Instance(){} public Instance(int label,double[] x){ this.label = label; th_logisticregression java
文章浏览阅读981次,点赞21次,收藏18次。本书是获得了很多读者好评的Linux经典畅销书**《Linux从入门到精通》的第2版**。下面我们来进行文件的恢复,执行下文中的lsof命令,在其返回结果中我们可以看到test-recovery.txt (deleted)被删除了,但是其存在一个进程tail使用它,tail进程的进程编号是1535。我们看到文件名为3的文件,就是我们刚刚“误删除”的文件,所以我们使用下面的cp命令把它恢复回去。命令进入该进程的文件目录下,1535是tail进程的进程id,这个文件目录里包含了若干该进程正在打开使用的文件。
文章浏览阅读10w+次,点赞12次,收藏72次。RTMP(Real Time Messaging Protocol)实时消息传输协议是Adobe公司提出得一种媒体流传输协议,其提供了一个双向得通道消息服务,意图在通信端之间传递带有时间信息得视频、音频和数据消息流,其通过对不同类型得消息分配不同得优先级,进而在网传能力限制下确定各种消息得传输次序。_rtmp
文章浏览阅读64次。2017年12月的计算机等级考试将要来临!出国留学网为考生们整理了2017年12月计算机一级MSOffice考试习题,希望能帮到大家,想了解更多计算机等级考试消息,请关注我们,我们会第一时间更新。2017年12月计算机一级MSOffice考试习题(二)一、单选题1). 计算机最主要的工作特点是( )。A.存储程序与自动控制B.高速度与高精度C.可靠性与可用性D.有记忆能力正确答案:A答案解析:计算...
文章浏览阅读356次。在学MYSQL的时候刚刚好看到了这个提权,很久之前用过别人现成的,但是一直时间没去细想, 这次就自己复现学习下。 0x00 UDF 什么是UDF? UDF (user defined function),即用户自定义函数。是通过添加新函数,对MySQL的功能进行扩充,就像使..._the provided input file '/usr/share/metasploit-framework/data/exploits/mysql
文章浏览阅读3.1w次,点赞71次,收藏485次。webService一 WebService概述1.1 WebService是什么WebService是一种跨编程语言和跨操作系统平台的远程调用技术。Web service是一个平台独立的,低耦合的,自包含的、基于可编程的web的应用程序,可使用开放的XML(标准通用标记语言下的一个子集)标准...
文章浏览阅读1w次。前言照例给出官网:Retrofit官网其实大家学习的时候,完全可以按照官网Introduction,自己写一个例子来运行。但是百密一疏,官网可能忘记添加了一句非常重要的话,导致你可能出现如下错误:Could not locate ResponseBody converter错误信息:Caused by: java.lang.IllegalArgumentException: Could not l_已添加addconverterfactory 但是 could not locate responsebody converter
文章浏览阅读1k次。一套键鼠控制Windows+Linux——Synergy在Windows10和Ubuntu18.04共控的实践Synergy简介准备工作(重要)Windows服务端配置Ubuntu客户端配置配置开机启动Synergy简介Synergy能够通过IP地址实现一套键鼠对多系统、多终端进行控制,免去了对不同终端操作时频繁切换键鼠的麻烦,可跨平台使用,拥有Linux、MacOS、Windows多个版本。Synergy应用分服务端和客户端,服务端即主控端,Synergy会共享连接服务端的键鼠给客户端终端使用。本文_linux 18.04 synergy
文章浏览阅读374次。写demo的时候遇到了很多问题,记录一下。安装nacos1.4.0配置mysql数据库,新建nacos_config数据库,并根据初始化脚本新建表,使配置从数据库读取,可单机模式启动也可以集群模式启动,启动时 ./start.sh -m standaloneapplication.properties 主要是db部分配置## Copyright 1999-2018 Alibaba Group Holding Ltd.## Licensed under the Apache License,_seata1.4.0 +nacos 集成
文章浏览阅读833次。iperf使用方法详解 iperf3是一款带宽测试工具,它支持调节各种参数,比如通信协议,数据包个数,发送持续时间,测试完会报告网络带宽,丢包率和其他参数。 安装 sudo apt-get install iperf3 iPerf3常用的参数: -c :指定客户端模式。例如:iperf3 -c 192.168.1.100。这将使用客户端模式连接到IP地址为192.16..._iperf客户端指定ip地址
文章浏览阅读7.4k次。 写这个函数目的不是为了和C/C++库中的函数在性能和安全性上一比高低,只是为了给那些喜欢探讨函数内部实现的网友,提供一种从浮点性到字符串转换的一种途径。 浮点数是有精度限制的,所以即使我们在使用C/C++中的sprintf或者cout 限制,当然这个精度限制是可以修改的。比方在C++中,我们可以cout.precision(10),不过这样设置的整个输出字符长度为10,而不是特定的小数点后1_c++浮点数 转 字符串 精度损失最小