I have an implementation of WallpaperService.Engine that uses JNI to create a C++ renderer:
Engine (Java) -> Renderer (C++)
If the renderer was Java code I could simply state
private Renderer renderer = new Renderer();
to make sure the renderer was created with my Engine and destroyed automatically when it's not needed any more. So what is the cleanest way to do this?
P.S.: I was thinking:
int rendererId = createNativeRenderer();
...
draw(rendererId); // call all native renderer methods specifying the object id
...
deleteNativeRenderer(rendererId);
But it's not very elegant since it requires explicit deletion, which is easy to forget.
Yes it's not very elegant, but it's by far the most reliable way. Java tries to be a hammer for every nail, so there is this thing called finalizer - an Object method called upon garbage collecting your instance. So it ideally does exactly what you need but practically better be avoided. If you read the related Javadoc carefully, you'll find out that:
Though, you can use finalizer for a safety check.
finalize()
and check the flag state there. If not marked as deleted, log nasty error