gpt4 book ai didi

Android Fragment 被销毁但收到 onActivityResult

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:37:59 26 4
gpt4 key购买 nike

感谢这个答案Android Fragment lifecycle issue (NullPointerException on onActivityResult)当我在调用 startActivityForResult 后在我的 fragment 中收到 NPE 时,我设法重新创建了一个场景。所以我有

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, PHOTO_SELECT_REQUEST_CODE);
break;

从我的 fragment 调用,然后我的 Activity 接收到 onPause、onStop 和 onDestroy,因此调用 startActivityForResult 的 fragment 也获得了 onDestroy。在我选择一张图片后,我在我的 Activity 上获得了一个新的 onCreate,然后我在我现在被销毁的原始 fragment 上获得了一个 public void onActivityResult

我的问题是,由于这可能(尽管很少见)情况,如何恢复传递给它们的整个 fragment 和对象堆栈,以及如何防止原始 fragment 泄漏?

最佳答案

当您的代码执行以下行时:

startActivityForResult(photoPickerIntent, PHOTO_SELECT_REQUEST_CODE);

您的 Activity 每次都会得到 onPause()onStop() 而不是 onDestroy()。如果 android 系统在那个运行时内存不足,那么你的 Activity 可能会得到 onDestroy()

为了保存 fragment 和 Activity 的状态并防止泄漏:

onSaveInstanceState(Bundle) 中保存您的状态

In situations where the system needs more memory it may kill paused processes (after onPause()) to reclaim resources. Because of this, you should be sure that all of your state is saved by the time you return from this function. In general onSaveInstanceState(Bundle) is used to save per-instance state in the activity and this method is used to store global persistent data (in content providers, files, etc.)

onRestoreInstanceState(Bundle) 中恢复你的状态

onRestoreInstanceState(Bundle) method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

这可以帮助您实现您的要求

关于Android Fragment 被销毁但收到 onActivityResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29465182/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com