我正在开发基于Android NFC的应用程序,要求从任何活动连续向SLIX-2(ICode)标签连续读/写数据。
到目前为止,应用程序开始初始化NFCManager,它完成了大部分的繁琐工作,以进行标签检测,不断轮询以进行状态检查,读取和写入数据。
BaseActivity使用其他必需的工作来初始化ANFCManager,例如挂起的重启意图,检查nfc适配器,enableForegroundDispatch,...
private fun initField() {
mNfcManager = ANfcManager(this)
}
private fun createPendingRestartIntent() {
pendingIntent = PendingIntent.getActivity(this, 0, Intent(this, javaClass)
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0
)
}
override fun onResume() {
super.onResume()
try {
if(mNfcManager.checkNfcPowerStatus()) // NfcAdapter enabled or not
setReadyToHandleTag()
else Log.w(TAG, "Nfc is not supported or disabled.")
} catch (e: AcmNfcManager.NfcNotEnabledException) {
Log.e(TAG, "Nfc not enabled", e)
}
}
private fun setReadyToHandleTag() {
try {
TECHLISTS = arrayOf(arrayOf(IsoDep::class.java.name), arrayOf(NfcV::class.java.name),
arrayOf(NfcA::class.java.name), arrayOf(NfcB::class.java.name),
arrayOf(NfcF::class.java.name),arrayOf(Ndef::class.java.name),
arrayOf(NdefFormatable::class.java.name))
val tagDetected = IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)
tagDetected.addCategory(Intent.CATEGORY_DEFAULT)
TAGFILTERS = arrayOf(tagDetected)
} catch (e: Exception) {
Log.e(TAG, "TECH or TAG filter no detected!!!" )
}
pendingIntent?.let { mNfcManager.enableForegroundDispatch(this, it, TAGFILTERS, TECHLISTS) }
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
nfcState = mNfcManager.filterIntent(intent)
dispatchActionOnTag(nfcState)
}
// this abs function will provide the Tag state in the corresponding class
abstract fun dispatchActionOnTag(tag: Boolean)
每个活动都有NfcListener用于标记检测,并将使用ANfcManager API进行读/写。同样,要连续检查标签是否存在,请在NFC Manager中使用具有循环器内部类的处理程序进行状态检查。
这是ActivityA内部的触发标记检测后的方法以及状态检查线程的函数,
override fun dispatchActionOnTag(tag: Boolean) {
mNfcStatus = tag
if (nfcStateListener() != null) {
nfcStateListener().updateNfcState(tag)
mNfcManager.startTagCheck() // presence check handler every x sec
}
}
在用于标记检测和存在检查的每个活动中都重复了相同的功能(有点不干净,但仍然可以使用),并基于对标记的读/写数据。
这是我的问题,
前提条件:
我的应用程序(产品)中的标签位于固定位置(粘贴在硬件中),除非更改标签,否则通常不会将其取出。
在某些情况下,可以在大部分ActivityB中取出Tag或ActivityC活动将在运行,这需要在这些活动中重复相同的回调代码。
必填:-从ActvityA-> ActivityB切换时,标签检测流程未完成(onNewIntent)或TAg没有从附近取出并再次点击。 如何将数据写入/读取标签?
ANFCManager,
class ANfcManager @Inject constructor(context: Context) {
private val mContext = context
private lateinit var nfcAdapter: NfcAdapter
private lateinit var mTag: Tag
private lateinit var iCodeTag: ICodeSlix2
private lateinit var icode: ICode
init {
val readPermission = ContextCompat.checkSelfPermission(
mContext,
Manifest.permission.WRITE_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED
if (!readPermission) {
ActivityCompat.requestPermissions(
mContext as Activity,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 113
)
}
/**
* initialize background thread for presence check every x seconds.
*/
val thread = HandlerThread("PresenceCheckThread")
thread.start()
mHandler = PresenceHandler(thread.looper)
}
fun enableForegroundDispatch(
activity: FragmentActivity, intent: PendingIntent,
filters: Array<IntentFilter>?, techLists: Array<Array<String>>?
) {
nfcAdapter.enableForegroundDispatch(activity, intent, filters, techLists)
}
fun disableForegroundDispatch(activity: Activity) {
nfcAdapter.disableForegroundDispatch(activity)
}
fun filterIntent(intent: Intent): Boolean {
val action = intent.action
if (NfcAdapter.ACTION_TECH_DISCOVERED == action
|| NfcAdapter.ACTION_TAG_DISCOVERED == action
|| NfcAdapter.ACTION_NDEF_DISCOVERED == action
) {
if (intent.hasExtra(NfcAdapter.EXTRA_TAG)) {
mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG)!!
return if (discoverTag()) {
Toast.makeText(mContext, "Tag detected.", Toast.LENGTH_SHORT).show()
true
} else {
ignoreTag()
false
}
}
}
return false
}
/**
* discover the Tag family.
*/
fun discoverTag(): Boolean {
icode = getTag(mTag)
if (ICodeSlix2::class.java.isInstance(icode))
iCodeTag = icode as ICodeSlix2
return iCodeTag != null
}
fun checkNfcPowerStatus(): Boolean {
return checkNfcPowerStatus(mContext)
}
/**
* Check Nfc status
*/
private fun checkNfcPowerStatus(context: Context?): Boolean {
nfcAdapter = NfcAdapter.getDefaultAdapter(context)
var enabled = false
if (nfcAdapter != null) {
enabled = nfcAdapter.isEnabled
}
return enabled
}
fun writeUpdateBlocks() {
try {
iCodeTag.connect()
.
. // proprietary code
.
}catch (e: IOException) {
e.printStackTrace()
Log.e(TAG, "IOException: ", e)
} catch (e: SmartCardException) {
e.printStackTrace()
Log.e(TAG, "SmartCardException: ", e)
} catch (e: IllegalArgumentException) {
e.printStackTrace()
Log.e(TAG, "IllegalArgumentException: ", e)
} catch (e: IllegalStateException) {
e.printStackTrace()
Log.e(TAG, "IllegalArgumentException: ", e)
} catch (e: IndexOutOfBoundsException) {
e.printStackTrace()
Log.e(TAG, "IndexOutOfBoundsException: ", e)
} finally {
iCodeTag.close()
}
}
必需:-从ActvityA-> ActivityB切换时,标签检测流没有完成(onNewIntent)或TAg没有从附近取出然后再次点击。如何将数据写入/读取标签?
所以Tag对象是一个Parcelable对象,只需将其从ActivityA传递给ActivityB,就无需重新发现它。
例如诸如此类(对不起Java而不是Kotlin)活动A
Intent intent = new Intent(getActivity(), ActivityB.class);
intent.putExtra("TAG", mTag);
startActivity(intent);
活动B中的onCreate
Intent intent = getIntent();
mTag = intent.getParcelableExtra("TAG")
// Start doing stuff with the Tag just like if you got it via discovery
// ANfcManager might need a `setTag` method to set it without discovery.
// or allow a Tag be be passed in the ANfcManager constructor
不是我会用enableForegroundDispatch
来读取标签,尤其是写标签,因为我发现它不太可靠,我建议使用enableReaderMode
,但是您仍然可以在活动之间传递标签对象。