片段中接收NFC的应用程序创建了托管活动的新实例

如何解决片段中接收NFC的应用程序创建了托管活动的新实例

打招呼中的人们

好吧,我得到了一个托管3个片段的活动(使用navController) 我需要读取其中一个托管片段(GameSessionFragment)中的NFC标签ID(EXTRA_ID)

我的问题是,每次我扫描新的NFC标签时,托管该片段(主机)的活动都会再次“创建”,以便使我脱离呈现的片段,并导航到“主机”活动,我试图避免重新创建主机活动的任何想法如何实现?

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

这是我的代码:

清单:

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

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </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,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,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)

    }

}

我还在这里Application receiving NFC always pops up new instance in front

但没有意识到实际要做的事情。

我读到有关使用的信息

mNfcAdapter!!.disableForegroundDispatch(getActivity())

但不确定那件事是否也会影响我。

更新:

感谢:安德鲁

非常感谢!! “ enableReaderMode”似乎就像我需要的东西一样,我成功读取了标签ID,但是同时发生了两个问题,当我扫描NFC标签时,我可以在“ println”中看到标签ID,到目前为止一切正常,即时通讯成功读取它,但是当我尝试将其传递到片段中的TextView时,它仅在刷新片段时才会发生,(还有第二个问题)我看到了那个textview几秒钟,但随后所有我的布局消失了(在“主机活动”中的所有片段中),

得到该消息“只有创建视图层次结构的原始线程才能触摸其视图”

我可以看到那些片段内部的功能,它只是消失的布局,希望您能理解我的意愿。能够帮助我解决我的问题,如果您认为有更好的方式来描述问题,我们欢迎您发言

感谢所有来帮助我们的人!

工作乐趣 您所需要的! '''

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.os.Bundle)

这会在您的应用程序中创建一个新线程来处理发现标签的情况,避免了使用Intents获取NFC数据时发生的创建/重新创建/暂停/恢复活动。

然后在onTagDiscovered回调方法中,对getId对象使用Tag https://developer.android.com/reference/android/nfc/Tag#getId()以获取与Extra_ID相同的数据

https://stackoverflow.com/a/64441986/2373819处使用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) {

因此,您需要使用一种方法来在线程之间传递数据。

一种简单的方法是使用runOnUIThread https://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);
  }
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res