欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ANativeWindow_fromSurface返回空指针的问题

程序员文章站 2022-03-29 16:05:28
...

转载至: http://www.xuebuyuan.com/2183201.html

最近碰到这个问题,给jni层传入SurfaceView的Surface指针后,使用ANativeWindow_fromSurface返回值为空,经过调试分析,发现有两个原因:

1.在非UI线程中,new SurfaceView 之后,马上传给ANativeWindow_fromSurface,结果是Surface还没创建好,可能在Creating状态,所以返回空值;

2.在UI线程中创建SurfaceView,然后在非UI线程中调用ANativeWindow_fromSurface,结果也会返回空值,原因是:

static sp<Surface> getSurface(JNIEnv* env, jobject clazz)
{
    sp<Surface> result(Surface_getSurface(env, clazz));
    if (result == 0) {
        /*
         * if this method is called from the WindowManager's process, it means
         * the client is is not remote, and therefore is allowed to have
         * a Surface (data), so we create it here.
         * If we don't have a SurfaceControl, it means we're in a different
         * process.
         */

        SurfaceControl* const control =
            (SurfaceControl*)env->GetIntField(clazz, so.surfaceControl);
        if (control) {
            result = control->getSurface();
            if (result != 0) {
                result->incStrong(clazz);
                env->SetIntField(clazz, so.surface, (int)result.get());
            }
        }
    }
    return result;
}

而情景就是,在onCreate函数中我使用findViewById来赋值时(xml中SurfaceView的visibility属性为visible,如果为gone还是会在UI线程中创建),在其他线程中调用ANativeWindow_fromSurface返回正确值,如果在onCreate函数中使用new SurfaceView时,同样在其他线程中调用ANativeWindow_fromSurface返回的是空指针。

总结ANativeWindow_fromSurface的使用方法:

1.如果在UI线程中创建SurfaceView,那么需要在UI线程中使用ANativeWindow_fromSurface;

2.如果在非UI线程中创建SurfaceView,那么需要等待SurfaceView创建完成之后,才能调用ANativeWindow_fromSurface,至于能不能在UI线程中调用ANativeWindow_fromSurface,那我就没试过了,有朋友试过的话,不妨告诉我。