Using async initialization is a recommended way for application development. It uses the OpenCV Manager to access OpenCV libraries externally installed in the target system.
Code snippet implementing the async initialization:
public class MainActivity extends Activity implements CvCameraViewListener2 {
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch(status) {
case LoaderCallbackInterface.SUCCESS:
Log.i(TAG,"OpenCV Manager Connected");
//from now onwards, you can use OpenCV API
Mat m = new Mat(5, 10, CvType.CV_8UC1, new Scalar(0));
break;
case LoaderCallbackInterface.INIT_FAILED:
Log.i(TAG,"Init Failed");
break;
case LoaderCallbackInterface.INSTALL_CANCELED:
Log.i(TAG,"Install Cancelled");
break;
case LoaderCallbackInterface.INCOMPATIBLE_MANAGER_VERSION:
Log.i(TAG,"Incompatible Version");
break;
case LoaderCallbackInterface.MARKET_ERROR:
Log.i(TAG,"Market Error");
break;
default:
Log.i(TAG,"OpenCV Manager Install");
super.onManagerConnected(status);
break;
}
}
};
@Override
public void onResume() {
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_1_0, this, mLoaderCallback);
}
...
}
In this case, our application works with OpenCV Manager in asynchronous fashion. OnManagerConnected
callback will be called in UI thread, when initialization finishes.
Please note, that it is not allowed to use OpenCV calls or load OpenCV-dependent native libs before invoking this callback. Load your own native libraries that depend on OpenCV after the successful OpenCV initialization.
Default BaseLoaderCallback
implementation treat application context as Activity
and calls Activity.finish()
method to exit in case of initialization failure. To override this behaviour you need to override finish()
method of BaseLoaderCallback
class and implement your own finalization method.
OpenCV Manager is an Android service targeted to manage OpenCV library binaries on end users devices. It allows sharing the OpenCV dynamic libraries between applications on the same device.
The Manager provides the following benefits:
The only disadvantage is that the user is prompted to download and extra app, so the user experience slightly decreases.
More info: Android OpenCV Manager
Updated 18/10/16:
There is a bug in the OpenCV Manager version distributed on Play Store (updated 21/09/15).
It affects only OpenCV 3.1.0 version. When you run some OpenCV functions you get aSIGSEGV
error. The version distributed with Android SDK works fine (OpenCV-android-sdk/apk/OpenCV_3.1.0_Manager_3.10_{platform}.apk
). It can be downloaded from OpenCV website.
More info: Issue #6247.