在片段中接收 NFC 的应用程序创建托管的新实例 activity

Application receiving NFC in fragment create new instance of hosted activity

向 Whosebug 中的人们问好

好吧,我得到了一个 activity,其中包含 3 个片段(带有 navController) 我需要读取其中一个托管片段 (GameSessionFragment)

中的 NFC 标签 ID(EXTRA_ID)

我的问题是,每次我扫描新的 NFC 标签时,托管片段(主机)的 activity 再次“创建”,这样它就可以让我脱离呈现的片段并导航到“主机”的起始目的地 Activity,我正在努力避免重新创建主机 activity 有什么办法可以实现吗?

如果我不清楚或者您认为我可能对我的问题有更好的解释,请写在上面, 另外,对不起我的英语..

这是我的代码:

清单:

<activity android:name=".Host" >
            <intent-filter>
                <action android:name="android.nfc.action.TAG_DISCOVERED" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

主持人Activity:

class Host : AppCompatActivity() {

    var fragment: Fragment? = null

    private var mAdapter: NfcAdapter? = null
    private var mPendingIntent: PendingIntent? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_host)

        //for hide the actionBar (contains Fragment name) on top of the screen
        val actionBar = supportActionBar
        actionBar?.hide()

        val navController = Navigation.findNavController(this, R.id.nav_host_fragment)
        val navView = findViewById<BottomNavigationView>(R.id.nav_view)
        navView?.setupWithNavController(navController)


        NavigationUI.setupWithNavController(navView, navController)


        //tries to stop poping the activity each time NFC Tag scanned
        mAdapter = NfcAdapter.getDefaultAdapter(this)

        mPendingIntent = PendingIntent.getActivity(
            this, 0,
            Intent(this, javaClass).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0
        )
       //toGameSession(whatToDO)


    }



    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        for (fragment in supportFragmentManager.fragments) {
            fragment.onActivityResult(requestCode, resultCode, data)
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)

        if (NfcAdapter.ACTION_NDEF_DISCOVERED == intent.action) {
            intent.getParcelableArrayExtra(NfcAdapter.EXTRA_ID)?.also { rawMessages ->
                val messages: List<NdefMessage> = rawMessages.map { it as NdefMessage }
                // Process the messages array.
                println(messages)

                if (fragment is UserStatusFragment) {
                    val my: UserStatusFragment = fragment as UserStatusFragment
                    // Pass intent or its data to the fragment's method
                    my.processNFC(intent.getStringExtra(messages.toString()))
                }

            }
        }
    }

}

这是我想要接收和使用 NFC 的片段 Extra_ID

GameSessionFragment

class GameSessionFragment : Fragment() {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null

    lateinit var nfcTagId : String

    private var mNfcAdapter: NfcAdapter? = null
    private var mPendingIntent: PendingIntent? = null
    private var mNdefPushMessage: NdefMessage? = null


    var mAuth: FirebaseAuth? = null
    lateinit var firebaseUser: FirebaseUser
    private lateinit var databaseReference: DatabaseReference

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
       
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

      
        getNfcTagID()

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_game_session, container, false)
    }


    private fun getNfcTagID(){
        val tagId : ByteArray? = activity?.intent?.getByteArrayExtra(NfcAdapter.EXTRA_ID)
        if (tagId != null){
            nfcTagId = tagId?.toHexString().toString()
            tv_status.text = nfcTagId


        }
    }

    fun ByteArray.toHexString() = joinToString("") { "%02x".format(it) }


    fun questPartFinish(questPart: String, useruid: String) {
//        val rootRef = FirebaseDatabase.getInstance().reference
//        val scoreRef = rootRef.child("Quests").child(useruid).child("$questPart+QuestItemScanned")
//        scoreRef.runTransaction(object : Handler(), Transaction.Handler {
//            override fun doTransaction(mutableData: MutableData): Transaction.Result {
//                val ifFinish =
//                    mutableData.getValue(Boolean::class.java) ?: return Transaction.success(mutableData)
//
//                mutableData.value = true
////                if (operation == "increaseScore") {
////                    mutableData.value = score + 50
////                } else if (operation == "decreaseScore") {
////                    mutableData.value = score - 1
////                }
//                return Transaction.success(mutableData)
//            }
//
//            override fun onComplete(
//                databaseError: DatabaseError?,
//                b: Boolean,
//                dataSnapshot: DataSnapshot?
//            ) {
//            }
//
//            override fun publish(p0: LogRecord?) {
//                TODO("Not yet implemented")
//            }
//
//            override fun flush() {
//                TODO("Not yet implemented")
//            }
//
//            override fun close() {
//                TODO("Not yet implemented")
//            }
//        })

        databaseReference.child("Quests").child(useruid)
            .child("$questPart" + "QuestItemScanned").setValue(true)

    }

}

我也看了这里

但没有意识到实际需要做什么..

我读过关于使用

mNfcAdapter!!.disableForegroundDispatch(getActivity())

但不确定那件事是否也影响到我..

更新:

感谢:安德鲁

非常感谢!! “enableReaderMode”似乎正是我需要的东西,我成功读取了标签 ID,但同时出现了两个问题,当我扫描 NFC 标签时,我可以在“println”中看到标签 ID,所以现在一切都很好,我成功读取了它,但是当我试图将它传递到片段中的 TextView 时,它只在我刷新片段时发生,(并且有第二个问题)我看到那个 textview 秒但是然后,所有我的布局消失了(在我主机的所有片段中 Activity),

收到消息“只有创建视图层次结构的原始线程才能触及它的视图”

我可以在那些片段工作中看到那个功能,它只是消失的布局,希望你理解我并且愿意。能够帮助我解决我的问题,如果您认为有更好的方式来描述问题,欢迎您说

感谢所有前来帮助的人!

工作乐趣 这就是你所需要的! '''

var mNfcAdapter:NfcAdapter? =空

    fun ByteArray.toHexString() = joinToString("") { "%02x".format(it) }

    fun scanForNfcTagId(activity : Activity){
                val options = Bundle()
                // READER_PRESENCE_CHECK_DELAY is a work around for a Bug in some NFC implementations.
                options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 1);

                mNfcAdapter = NfcAdapter.getDefaultAdapter(activity)

                val flags =
                    NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS or
                            NfcAdapter.FLAG_READER_NFC_A or
                            NfcAdapter.FLAG_READER_NFC_B or
                            NfcAdapter.FLAG_READER_NFC_F or
                            NfcAdapter.FLAG_READER_NFC_V or
                            NfcAdapter.FLAG_READER_NFC_BARCODE


                mNfcAdapter!!.enableReaderMode(activity, NfcAdapter.ReaderCallback { tag ->
                    activity?.runOnUiThread {
                        Log.d("WTF", "Tag discovered")
                        nfcTagId = (tag.id).toHexString()
                        Toast.makeText(
                            activity,
                            "tag detected",
                            Toast.LENGTH_SHORT
                        ).show()


                        if (!actualQuest.firstQuestItemScanned) {
                            hatCallBackAction(activity)

                        } else if (!actualQuest.secondQuestItemScanned) {
                            println("scan for pants")
                            pantsCallBackAction(activity)

                        } else if (!actualQuest.thirdQuestItemScanned) {
                            println("scan for shirt")
                            shirtCallBackAction(activity)
                        } else {
                            println("actualQuest" + actualQuest)
                            Toast.makeText(
                                activity,
                                "Quest is Finish! no more to search here",
                                Toast.LENGTH_LONG
                            ).show()
                        }
                    }
                }, flags, null)
            }

'''

使用更新更好的 enableReaderMode API 进行 NFC https://developer.android.com/reference/android/nfc/NfcAdapter#enableReaderMode(android.app.Activity,%20android.nfc.NfcAdapter.ReaderCallback,%20int,%20android.os.Bundle)

这会在您的应用程序中创建一个新线程来处理发现标签时的情况,避免使用 Intents 获取 NFC 数据时发生的 activity creating/recreating/pausing/resuming。

然后在 onTagDiscovered 回调方法中使用 getId https://developer.android.com/reference/android/nfc/Tag#getId()Tag 对象上获得与 Extra_ID

相同的数据

使用 enableReaderMode 的示例位于

更新

如答案中所述,创建了一个新线程来处理 NFC 数据,只有 UI 线程可以更新 UI

同样在示例代码的注释中


// This gets run in a new thread on Tag detection
// Thus cannot directly interact with the UI Thread
public void onTagDiscovered(Tag tag) {

所以你需要使用一种方法来在线程之间传递数据。

简单的方法就是使用runOnUIThreadhttps://developer.android.com/reference/android/app/Activity#runOnUiThread(java.lang.Runnable)

例如

runOnUiThread(new Runnable() {
  @Override
  public void run() {
    // Set the value of the ID to the textview
    textview.setText(iDtext);
  }
});