通过所有活动检测NFC标签

时间:2020-04-20 18:54:52

标签: android nfc

我正在开发基于Android NFC的应用程序,要求从任何活动连续向SLIX-2(ICode)标签读取/写入数据。

从现在开始,应用程序开始初始化NFCManager,该任务将执行大部分繁重的工作以进行Tag检测,连续轮询以进行状态检查,读取和写入数据。

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中使用带有Looper内部类的处理程序进行状态检查。

这是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()
}

}

2 个答案:

答案 0 :(得分:1)

必需:-从ActvityA-> ActivityB切换时,标签检测 流没有完成(onNewIntent)或TAg没有从附近取出 然后再次点击。如何将数据写入/读取标签?

因此Tag对象是一个Parcelable对象,只需将其从ActivityA传递到ActivityB,就无需重新发现它。

例如诸如此类(对不起Java而不是Kotlin)
活动A

Intent intent = new Intent(getActivity(), ActivityB.class);
intent.putExtra("TAG", mTag);
startActivity(intent);

ActivityB 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,但是您仍然可以在活动之间传递标签对象。

答案 1 :(得分:0)

很快就将Manager类转换为Singleton,其余的都保持不变。

BaseActivity,

fun initField() {
   mNfcManager = ANfcManager.getInstance(this)
}

class ANfcManager private constructor(context: Context){

companion object : SingletonHolder<ANfcManager, Context>(::ANfcManager) {
        val TAG = ANfcManager::class.java.simpleName
    }

   init{
     mContext = context
     .
     .
     .
   }
}