关于魅族手机无法获取Surface的问题

近期在app_process运行进程的问题比较多。

这边有一个小问题,就是对于魅族手机无法getSuface的问题。具体出问题的代码:

ImageReader mImageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2);

Surface surface = mImageReader.getSurface();                  

System.out.Println(surface)     

这样最终输出的结果是null。

在Android Studio中查看对应的代码,在初始化ImageReader对象的时候surface就由内部函数创建出来,而此时获取的是空的,难免是手机系统中改写内部函数或者出现了什么问题:

protected ImageReader(int width, int height, int format, int maxImages, long usage) {
        mWidth = width;
        mHeight = height;
        mFormat = format;
        mMaxImages = maxImages;

        if (width < 1 || height < 1) {
            throw new IllegalArgumentException(
                "The image dimensions must be positive");
        }
        if (mMaxImages < 1) {
            throw new IllegalArgumentException(
                "Maximum outstanding image count must be at least 1");
        }

        if (format == ImageFormat.NV21) {
            throw new IllegalArgumentException(
                    "NV21 format is not supported");
        }

        mNumPlanes = ImageUtils.getNumPlanesForFormat(mFormat);

        nativeInit(new WeakReference<>(this), width, height, format, maxImages, usage);

        mSurface = nativeGetSurface();

        mIsReaderValid = true;
        // Estimate the native buffer allocation size and register it so it gets accounted for
        // during GC. Note that this doesn't include the buffers required by the buffer queue
        // itself and the buffers requested by the producer.
        // Only include memory for 1 buffer, since actually accounting for the memory used is
        // complex, and 1 buffer is enough for the VM to treat the ImageReader as being of some
        // size.
        mEstimatedNativeAllocBytes = ImageUtils.getEstimatedNativeAllocBytes(
                width, height, format, /*buffer count*/ 1);
        VMRuntime.getRuntime().registerNativeAllocation(mEstimatedNativeAllocBytes);
    }

但是在具体的Activity应用中直接获取对应的surface可以输出相应的地址。想必又是app_process的权限或执行中的问题。

此处解决方法为调用:

Looper.prepareMainLooper();

使得整个app_process进程被标记为应用的主looper,这样就可以规避在魅族手机上的问题了。

具体的解释为:


    /**
     * Initialize the current thread as a looper, marking it as an
     * application's main looper. The main looper for your application
     * is created by the Android environment, so you should never need
     * to call this function yourself.  See also: {@link #prepare()}
     */
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

猜你喜欢

转载自blog.csdn.net/u013379032/article/details/123402866