Some time ago I studied android and encountered trouble in operating surface on jni, mainly because the basic of C ++ is too poor, Surface. cpp reads n times and tries to pass the Surface from the Java end based on the information found on the Internet, and then performs operations on the jni end. But I always encounter various exceptions. I got stuck for seven days before and after, and finally solved the problem. releasing this method will always be helpful to some friends.
In fact, it is not original, but there are 1000 posts on the Internet, and 999 are all about the same method, but I cannot succeed here. Finally, I accidentally saw an e-article post that day. Someone analyzed libjnivideo. so of havlenapetr and then released the ta method. I wanted to be simple:
Static android: sp <android: Surface> native_surface;
Static android: Surface * getNativeSurface (JNIEnv * env, jobject jsurface, jint version)
{
Jclass clazz = env-> FindClass ("android/view/Surface ");
JfieldID field_surface;
If (version <= 8)
{
Field_surface = env-> GetFieldID (clazz, "mSurface", "I ");
}
Else
Field_surface = env-> GetFieldID (clazz, ANDROID_VIEW_SURFACE_JNI_ID, "I ");
If (field_surface = NULL)
{
Return NULL;
}
Return (android: Surface *) env-> GetIntField (jsurface, field_surface );
}
Int setSurface (JNIEnv * env, jobject jsurface, jint version)
{
Native_surface = getNativeSurface (env, jsurface, version );
If (android: Surface: isValid (native_surface ))
{
_ Android_log_print (ANDROID_LOG_INFO, "libjni", "native_surface is valid ");
Return 1;
}
Else
_ Android_log_print (ANDROID_LOG_ERROR, "libjni", "native_surface is invalid ");
Return 0;
}
Jsurface is passed from the Java end, And the native_surface here is the native surface we want. Why should I pass a version? For Versions later than android, there is no "mSurface" in android. view. Surface, but a constant ANDROID_VIEW_SURFACE_JNI_ID is used to distinguish the next version.
Then we found that the jni side is quite simple to operate the surface, at least displaying images and the like is very easy:
Static android: Surface: SurfaceInfo info;
Static android: Region dirtyRegion;
Perform the following initialization:
DirtyRegion. set (android: Rect (0x3FFF, 0x3FFF ));
Then
Native_surface-> lock (& info, & dirtyRegion, true );
Memcpy (info. bits, buf, bufSize );
Native_surface-> unlockAndPost ();
It is displayed.
Author: ljplum