gpt4 book ai didi

java - 安卓NDK : How to clean up native code after restarting activity?

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

全部,

我知道默认情况下,当屏幕方向改变或键盘滑入或滑出时, Activity 将被终止并重新启动。 (参见 Activity restart on rotation Android )。我的问题是,从 native 代码的角度来看,处理此问题的正确方法是什么?例如如果我有一个加载 native 库的静态 block 并且我的应用程序重新启动,我如何确保 native 土地上的任何内存都得到适当处理?问题是

When we rotate the device, it looks like a separate Thread pool is created and the old ones are never removed. This means that every time someone turns the device, we have a ton more threads sitting idle and taking up memory

我如何确保不会发生这种情况?我从 JNIExample page 底部看到一些注释:

[*]Unresolved issues and bugs Even though the example is fully functional, there are a couple unresolved issues remaining, which I was not able to figure out so far. Problems appear when you start the activity, then press the Back button to hide it, and then start it again. In my experience, calls to native functions in such restarted activity will fail spectacularly. callVoid() simply crashes with a segmentation fault, while calls to getNewData() and getDataString() cause JVM to abort with an error, because it is no longer happy with the globally cached object reference. It appears that activity restart somehow invalidates our cached object references, even though they are protected with NewGlobalRef(), and the activity is running within the original JVM (activity restart does not mean that JVM itself is restarted). I don't have a good explanation on why that happens, so if you have any ideas, please let me know.

这个问题解决了吗?

最佳答案

在 Android NDK 中重启很烦人。您拥有的任何静态数据都会保留下来,因为它会重用该过程,因此您需要手动重置任何在新运行时无效的内容(如任何 OpenGL 纹理或顶点缓冲对象)。它为您提供了一个新的 Java 线程和新的 Java 应用程序以及其他对象,因此还需要清除对您的应用程序新实例中新对象的任何缓存全局引用。

所以我使用的策略是双重的:最小化重新启动,并在重新启动时核对所有内容。

您可以通过处理应用程序内的 configChanges 来最大程度地减少重启,正如您在对所链接问题的回答中所说的那样。然后打开键盘或旋转键盘不会导致应用重新启动,这对于任何具有重要启动时间的应用来说都应该如此。

当我检测到我的应用程序的一个新实例已启动时,我会释放旧实例中的所有关键内容,包括释放我通过 NewGlobalRef 保留的所有 Java 对象。我试图尽量减少静态数据,但在我确实保留静态对象的少数不可避免的地方,当我检测到新实例启动时,我会清除它们。

一旦不再有对旧线程的引用(即,一旦您释放了所有 NewGlobalRef 对象),旧线程就应该消失。

关于java - 安卓NDK : How to clean up native code after restarting activity?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3991193/

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