Opencv4Android摆脱OpenCV manager.apk的安装

我们知道,在Android手机上利用Opencv来进行相关开发的时候,除了要安装自己的应用外,还要安装一个apk-----OpenCV manager.apk。这样就造成很差的用户体验,所以,本文将教会大家怎么摆脱这个困境。

不知道大家有没有发现,在这个路径:./sdk/java/bin/aidl/org/opencv/engine/中有一个aidl文件 OpenCVEngineInterface.aidl,它里面是这么定义的:

package org.opencv.engine;

/**
* Class provides a Java interface for OpenCV Engine Service. It's synchronous with native OpenCVEngine class.
*/
interface OpenCVEngineInterface
{
    /**
    * @return Returns service version.
    */
    int getEngineVersion();

    /**
    * Finds an installed OpenCV library.
    * @param OpenCV version.
    * @return Returns path to OpenCV native libs or an empty string if OpenCV can not be found.
    */
    String getLibPathByVersion(String version);

    /**
    * Tries to install defined version of OpenCV from Google Play Market.
    * @param OpenCV version.
    * @return Returns true if installation was successful or OpenCV package has been already installed.
    */
    boolean installVersion(String version);

    /**
    * Returns list of libraries in loading order, separated by semicolon.
    * @param OpenCV version.
    * @return Returns names of OpenCV libraries, separated by semicolon.
    */
    String getLibraryList(String version);
}


很明显,Opencv4Android SDK是通过aidl文件来与OpenCV manager这个应用进行跨进程通信。

其实,Opencv manager这个应用为我们自己开发的应用提供了库支持。利用adb命令,进入OpenCV manager应用包的lib路径查看一下:

在lib目录下有文件:libopencv_java3.so这个动态链库。如下图,我们以module的方式将Opencv sdk和lib下的库导入到我们的工程中:

Opencv4Android摆脱OpenCV manager.apk的安装_第1张图片

然后在程序中进行加载调用:

private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS: {
                    Log.i("OpenCV", "OpenCV loaded successfully");
                    mOpenCvCameraView.enableView();
                }
                break;
                default: {
                    super.onManagerConnected(status);
                }
                break;
            }
        }
    };

@Override
    protected void onResume() {
        super.onResume();
        if (!OpenCVLoader.initDebug()) {
            Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_2_0, this, mLoaderCallback);
        } else {
            Log.d(TAG, "OpenCV library found inside package. Using it!");
            mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
        }
        
    }

然后在这个module的build.gradle文件中加入对库的引用:

sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }

BTW:如果在我们自己的应用中加入这些库,势必会导致我们自己的应用变得很大很大,也是一种弊端。但毕竟鱼与熊掌不可兼得,大家都懂。


希望这篇文章对大家有所启发,谢谢!


你可能感兴趣的:(Opencv4Android)