To implement a callback function from the native code to Java code, I have to create a global reference using NewGloabRef
. From the memory profile , I found that ,once I called env->NewGlobalRef(weak_this)
, even it was a weak reference of the player object, the Player object will be available as Root Objects, which I think will prevent it from being garbage collected.
But my understanding is the weak reference won't prevent the object from garbage collected.
//java code
Player{
native_init(new WeakReference(this)),
}
//JNi code
//listener
Listener::Listener(jobject weak_this)
{
//will use mObject for callback
mObject = env->NewGlobalRef(weak_this);
}
xxxx_Player_native_init(xxxx. Object weak_this)
{
Listener l = new Listener(weak_this);
}
EDIT:
memory profile :
Root Object 0x2C820E10 <com/trident/tv/media/player/JniTPlayer>
com/trident/tv/media/player/JniTPlayer.trace : 0x2C83CC54 <java/lang/String>
com/trident/tv/media/player/JniTPlayer.listenerList : 0x2C820E64 <java/util/Vector>
log of JNI
[JNI] NewGlobalRef(0x2C820E10 [com/trident/tv/media/player/JniTPlayer]) : 0x2C820E10