Handling onNewIntent in Fragment

后端 未结 3 1331
时光取名叫无心
时光取名叫无心 2021-01-17 08:28

I am writing an application that uses NFC to read some data stored on it. My application uses Fragments and Fragment don\'t come with onNewIntent() method. Since, the data I

3条回答
  •  别那么骄傲
    2021-01-17 09:00

    There is at least one alternative: From Activity.onNewIntent documentation:

    An activity will always be paused before receiving a new intent, so you can count on onResume() being called after this method.

    Note that getIntent() still returns the original Intent. You can use setIntent(Intent) to update it to this new Intent.

    FragmentActivity.onNewIntent documentation is different but I don't think it contradicts the above statements. I also make the assumption that Fragment.onResume will be called after FragmentActivity.onResume, even though the documentation seems a little fussy to me, though my tests confirm this assumption. Based on this I updated the Intent in the activity like so (examples in Kotlin)

    override fun onNewIntent(intent: Intent?) {
        setIntent(intent)
        super.onNewIntent(intent)
    }
    

    And in Fragment.onResume I could handle the new intent like so

    override fun onResume() {
        super.onResume()
        doStuff(activity.intent)
    }
    

    This way the activity don't need to know about what fragments it holds.

提交回复
热议问题