Android Open Source - android-opencv-template Async Service Helper






From Project

Back to project page android-opencv-template.

License

The source code is released under:

MIT License

If you think the Android project android-opencv-template listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package org.opencv.android;
//w  ww  . ja v a 2s .  com
import java.io.File;
import java.util.StringTokenizer;

import org.opencv.core.Core;
import org.opencv.engine.OpenCVEngineInterface;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

class AsyncServiceHelper
{
    public static boolean initOpenCV(String Version, final Context AppContext,
            final LoaderCallbackInterface Callback)
    {
        AsyncServiceHelper helper = new AsyncServiceHelper(Version, AppContext, Callback);
        if (AppContext.bindService(new Intent("org.opencv.engine.BIND"),
                helper.mServiceConnection, Context.BIND_AUTO_CREATE))
        {
            return true;
        }
        else
        {
            AppContext.unbindService(helper.mServiceConnection);
            InstallService(AppContext, Callback);
            return false;
        }
    }

    protected AsyncServiceHelper(String Version, Context AppContext, LoaderCallbackInterface Callback)
    {
        mOpenCVersion = Version;
        mUserAppCallback = Callback;
        mAppContext = AppContext;
    }

    protected static final String TAG = "OpenCVManager/Helper";
    protected static final int MINIMUM_ENGINE_VERSION = 2;
    protected OpenCVEngineInterface mEngineService;
    protected LoaderCallbackInterface mUserAppCallback;
    protected String mOpenCVersion;
    protected Context mAppContext;
    protected static boolean mServiceInstallationProgress = false;
    protected static boolean mLibraryInstallationProgress = false;

    protected static boolean InstallServiceQuiet(Context context)
    {
        boolean result = true;
        try
        {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(OPEN_CV_SERVICE_URL));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
        catch(Exception e)
        {
            result = false;
        }

        return result;
    }

    protected static void InstallService(final Context AppContext, final LoaderCallbackInterface Callback)
    {
        if (!mServiceInstallationProgress)
        {
                Log.d(TAG, "Request new service installation");
                InstallCallbackInterface InstallQuery = new InstallCallbackInterface() {
                private LoaderCallbackInterface mUserAppCallback = Callback;
                public String getPackageName()
                {
                    return "OpenCV Manager";
                }
                public void install() {
                    Log.d(TAG, "Trying to install OpenCV Manager via Google Play");

                    boolean result = InstallServiceQuiet(AppContext);
                    if (result)
                    {
                        mServiceInstallationProgress = true;
                        Log.d(TAG, "Package installation started");
                    }
                    else
                    {
                        Log.d(TAG, "OpenCV package was not installed!");
                        int Status = LoaderCallbackInterface.MARKET_ERROR;
                        Log.d(TAG, "Init finished with status " + Status);
                        Log.d(TAG, "Unbind from service");
                        Log.d(TAG, "Calling using callback");
                        mUserAppCallback.onManagerConnected(Status);
                    }
                }

                public void cancel()
                {
                    Log.d(TAG, "OpenCV library installation was canceled");
                    int Status = LoaderCallbackInterface.INSTALL_CANCELED;
                    Log.d(TAG, "Init finished with status " + Status);
                    Log.d(TAG, "Calling using callback");
                    mUserAppCallback.onManagerConnected(Status);
                }

                public void wait_install()
                {
                    Log.e(TAG, "Instalation was not started! Nothing to wait!");
                }
            };

            Callback.onPackageInstall(InstallCallbackInterface.NEW_INSTALLATION, InstallQuery);
        }
        else
        {
            Log.d(TAG, "Waiting current installation process");
            InstallCallbackInterface WaitQuery = new InstallCallbackInterface() {
                private LoaderCallbackInterface mUserAppCallback = Callback;
                public String getPackageName()
                {
                    return "OpenCV Manager";
                }
                public void install()
                {
                    Log.e(TAG, "Nothing to install we just wait current installation");
                }
                public void cancel()
                {
                    Log.d(TAG, "Wating for OpenCV canceled by user");
                    mServiceInstallationProgress = false;
                    int Status = LoaderCallbackInterface.INSTALL_CANCELED;
                    Log.d(TAG, "Init finished with status " + Status);
                    Log.d(TAG, "Calling using callback");
                    mUserAppCallback.onManagerConnected(Status);
                }
                public void wait_install()
                {
                     InstallServiceQuiet(AppContext);
                }
            };

            Callback.onPackageInstall(InstallCallbackInterface.INSTALLATION_PROGRESS, WaitQuery);
        }
    }

    /**
     *  URL of OpenCV Manager page on Google Play Market.
     */
    protected static final String OPEN_CV_SERVICE_URL = "market://details?id=org.opencv.engine";

    protected ServiceConnection mServiceConnection = new ServiceConnection()
    {
        public void onServiceConnected(ComponentName className, IBinder service)
        {
            Log.d(TAG, "Service connection created");
            mEngineService = OpenCVEngineInterface.Stub.asInterface(service);
            if (null == mEngineService)
            {
                Log.d(TAG, "OpenCV Manager Service connection fails. May be service was not installed?");
                InstallService(mAppContext, mUserAppCallback);
            }
            else
            {
                mServiceInstallationProgress = false;
                try
                {
                    if (mEngineService.getEngineVersion() < MINIMUM_ENGINE_VERSION)
                    {
                        Log.d(TAG, "Init finished with status " + LoaderCallbackInterface.INCOMPATIBLE_MANAGER_VERSION);
                        Log.d(TAG, "Unbind from service");
                        mAppContext.unbindService(mServiceConnection);
                        Log.d(TAG, "Calling using callback");
                        mUserAppCallback.onManagerConnected(LoaderCallbackInterface.INCOMPATIBLE_MANAGER_VERSION);
                        return;
                    }

                    Log.d(TAG, "Trying to get library path");
                    String path = mEngineService.getLibPathByVersion(mOpenCVersion);
                    if ((null == path) || (path.length() == 0))
                    {
                        if (!mLibraryInstallationProgress)
                        {
                            InstallCallbackInterface InstallQuery = new InstallCallbackInterface() {
                                public String getPackageName()
                                {
                                    return "OpenCV library";
                                }
                                public void install() {
                                    Log.d(TAG, "Trying to install OpenCV lib via Google Play");
                                    try
                                    {
                                        if (mEngineService.installVersion(mOpenCVersion))
                                        {
                                            mLibraryInstallationProgress = true;
                                            Log.d(TAG, "Package installation statred");
                                            Log.d(TAG, "Unbind from service");
                                            mAppContext.unbindService(mServiceConnection);
                                        }
                                        else
                                        {
                                            Log.d(TAG, "OpenCV package was not installed!");
                                            Log.d(TAG, "Init finished with status " + LoaderCallbackInterface.MARKET_ERROR);
                                            Log.d(TAG, "Unbind from service");
                                            mAppContext.unbindService(mServiceConnection);
                                            Log.d(TAG, "Calling using callback");
                                            mUserAppCallback.onManagerConnected(LoaderCallbackInterface.MARKET_ERROR);
                                        }
                                    } catch (RemoteException e) {
                                        e.printStackTrace();;
                                        Log.d(TAG, "Init finished with status " + LoaderCallbackInterface.INIT_FAILED);
                                        Log.d(TAG, "Unbind from service");
                                        mAppContext.unbindService(mServiceConnection);
                                        Log.d(TAG, "Calling using callback");
                                        mUserAppCallback.onManagerConnected(LoaderCallbackInterface.INIT_FAILED);
                                    }
                                }
                                public void cancel() {
                                    Log.d(TAG, "OpenCV library installation was canceled");
                                    Log.d(TAG, "Init finished with status " + LoaderCallbackInterface.INSTALL_CANCELED);
                                    Log.d(TAG, "Unbind from service");
                                    mAppContext.unbindService(mServiceConnection);
                                    Log.d(TAG, "Calling using callback");
                                    mUserAppCallback.onManagerConnected(LoaderCallbackInterface.INSTALL_CANCELED);
                                }
                                public void wait_install() {
                                    Log.e(TAG, "Instalation was not started! Nothing to wait!");
                                }
                            };

                            mUserAppCallback.onPackageInstall(InstallCallbackInterface.NEW_INSTALLATION, InstallQuery);
                        }
                        else
                        {
                            InstallCallbackInterface WaitQuery = new InstallCallbackInterface() {
                                public String getPackageName()
                                {
                                    return "OpenCV library";
                                }

                                public void install() {
                                    Log.e(TAG, "Nothing to install we just wait current installation");
                                }
                                public void cancel()
                                {
                                    Log.d(TAG, "OpenCV library installation was canceled");
                                    mLibraryInstallationProgress = false;
                                    Log.d(TAG, "Init finished with status " + LoaderCallbackInterface.INSTALL_CANCELED);
                                    Log.d(TAG, "Unbind from service");
                                    mAppContext.unbindService(mServiceConnection);
                                    Log.d(TAG, "Calling using callback");
                                        mUserAppCallback.onManagerConnected(LoaderCallbackInterface.INSTALL_CANCELED);
                                }
                                public void wait_install() {
                                    Log.d(TAG, "Waiting for current installation");
                                    try
                                    {
                                        if (!mEngineService.installVersion(mOpenCVersion))
                                        {
                                            Log.d(TAG, "OpenCV package was not installed!");
                                            Log.d(TAG, "Init finished with status " + LoaderCallbackInterface.MARKET_ERROR);
                                            Log.d(TAG, "Calling using callback");
                                            mUserAppCallback.onManagerConnected(LoaderCallbackInterface.MARKET_ERROR);
                                        }
                                        else
                                        {
                                            Log.d(TAG, "Wating for package installation");
                                        }

                                        Log.d(TAG, "Unbind from service");
                                        mAppContext.unbindService(mServiceConnection);

                                    } catch (RemoteException e) {
                                        e.printStackTrace();
                                        Log.d(TAG, "Init finished with status " + LoaderCallbackInterface.INIT_FAILED);
                                        Log.d(TAG, "Unbind from service");
                                        mAppContext.unbindService(mServiceConnection);
                                        Log.d(TAG, "Calling using callback");
                                        mUserAppCallback.onManagerConnected(LoaderCallbackInterface.INIT_FAILED);
                                    }
                               }
                            };

                            mUserAppCallback.onPackageInstall(InstallCallbackInterface.INSTALLATION_PROGRESS, WaitQuery);
                        }
                        return;
                    }
                    else
                    {
                        Log.d(TAG, "Trying to get library list");
                        mLibraryInstallationProgress = false;
                        String libs = mEngineService.getLibraryList(mOpenCVersion);
                        Log.d(TAG, "Library list: \"" + libs + "\"");
                        Log.d(TAG, "First attempt to load libs");
                        int status;
                        if (initOpenCVLibs(path, libs))
                        {
                            Log.d(TAG, "First attempt to load libs is OK");
                            String eol = System.getProperty("line.separator");
                            for (String str : Core.getBuildInformation().split(eol))
                                Log.i(TAG, str);

                            status = LoaderCallbackInterface.SUCCESS;
                        }
                        else
                        {
                            Log.d(TAG, "First attempt to load libs fails");
                            status = LoaderCallbackInterface.INIT_FAILED;
                        }

                        Log.d(TAG, "Init finished with status " + status);
                        Log.d(TAG, "Unbind from service");
                        mAppContext.unbindService(mServiceConnection);
                        Log.d(TAG, "Calling using callback");
                        mUserAppCallback.onManagerConnected(status);
                    }
                }
                catch (RemoteException e)
                {
                    e.printStackTrace();
                    Log.d(TAG, "Init finished with status " + LoaderCallbackInterface.INIT_FAILED);
                    Log.d(TAG, "Unbind from service");
                    mAppContext.unbindService(mServiceConnection);
                    Log.d(TAG, "Calling using callback");
                    mUserAppCallback.onManagerConnected(LoaderCallbackInterface.INIT_FAILED);
                }
            }
        }

        public void onServiceDisconnected(ComponentName className)
        {
            mEngineService = null;
        }
    };

    private boolean loadLibrary(String AbsPath)
    {
        boolean result = true;

        Log.d(TAG, "Trying to load library " + AbsPath);
        try
        {
            System.load(AbsPath);
            Log.d(TAG, "OpenCV libs init was ok!");
        }
        catch(UnsatisfiedLinkError e)
        {
            Log.d(TAG, "Cannot load library \"" + AbsPath + "\"");
            e.printStackTrace();
            result &= false;
        }

        return result;
    }

    private boolean initOpenCVLibs(String Path, String Libs)
    {
        Log.d(TAG, "Trying to init OpenCV libs");
        if ((null != Path) && (Path.length() != 0))
        {
            boolean result = true;
            if ((null != Libs) && (Libs.length() != 0))
            {
                Log.d(TAG, "Trying to load libs by dependency list");
                StringTokenizer splitter = new StringTokenizer(Libs, ";");
                while(splitter.hasMoreTokens())
                {
                    String AbsLibraryPath = Path + File.separator + splitter.nextToken();
                    result &= loadLibrary(AbsLibraryPath);
                }
            }
            else
            {
                // If the dependencies list is not defined or empty.
                String AbsLibraryPath = Path + File.separator + "libopencv_java.so";
                result &= loadLibrary(AbsLibraryPath);
            }

            return result;
        }
        else
        {
            Log.d(TAG, "Library path \"" + Path + "\" is empty");
            return false;
        }
    }
}




Java Source Code List

com.floatlearning.android_opencv_template.MainActivity.java
org.opencv.android.AsyncServiceHelper.java
org.opencv.android.BaseLoaderCallback.java
org.opencv.android.CameraBridgeViewBase.java
org.opencv.android.FpsMeter.java
org.opencv.android.InstallCallbackInterface.java
org.opencv.android.JavaCameraView.java
org.opencv.android.LoaderCallbackInterface.java
org.opencv.android.NativeCameraView.java
org.opencv.android.OpenCVLoader.java
org.opencv.android.StaticHelper.java
org.opencv.android.Utils.java
org.opencv.calib3d.Calib3d.java
org.opencv.calib3d.StereoBM.java
org.opencv.calib3d.StereoSGBM.java
org.opencv.contrib.Contrib.java
org.opencv.contrib.FaceRecognizer.java
org.opencv.contrib.StereoVar.java
org.opencv.core.Algorithm.java
org.opencv.core.Core.java
org.opencv.core.CvException.java
org.opencv.core.CvType.java
org.opencv.core.MatOfByte.java
org.opencv.core.MatOfDMatch.java
org.opencv.core.MatOfDouble.java
org.opencv.core.MatOfFloat4.java
org.opencv.core.MatOfFloat6.java
org.opencv.core.MatOfFloat.java
org.opencv.core.MatOfInt4.java
org.opencv.core.MatOfInt.java
org.opencv.core.MatOfKeyPoint.java
org.opencv.core.MatOfPoint2f.java
org.opencv.core.MatOfPoint3.java
org.opencv.core.MatOfPoint3f.java
org.opencv.core.MatOfPoint.java
org.opencv.core.MatOfRect.java
org.opencv.core.Mat.java
org.opencv.core.Point3.java
org.opencv.core.Point.java
org.opencv.core.Range.java
org.opencv.core.Rect.java
org.opencv.core.RotatedRect.java
org.opencv.core.Scalar.java
org.opencv.core.Size.java
org.opencv.core.TermCriteria.java
org.opencv.features2d.DMatch.java
org.opencv.features2d.DescriptorExtractor.java
org.opencv.features2d.DescriptorMatcher.java
org.opencv.features2d.FeatureDetector.java
org.opencv.features2d.Features2d.java
org.opencv.features2d.GenericDescriptorMatcher.java
org.opencv.features2d.KeyPoint.java
org.opencv.gpu.DeviceInfo.java
org.opencv.gpu.Gpu.java
org.opencv.gpu.TargetArchs.java
org.opencv.highgui.Highgui.java
org.opencv.highgui.VideoCapture.java
org.opencv.imgproc.CLAHE.java
org.opencv.imgproc.Imgproc.java
org.opencv.imgproc.Moments.java
org.opencv.imgproc.Subdiv2D.java
org.opencv.ml.CvANN_MLP_TrainParams.java
org.opencv.ml.CvANN_MLP.java
org.opencv.ml.CvBoostParams.java
org.opencv.ml.CvBoost.java
org.opencv.ml.CvDTreeParams.java
org.opencv.ml.CvDTree.java
org.opencv.ml.CvERTrees.java
org.opencv.ml.CvGBTreesParams.java
org.opencv.ml.CvGBTrees.java
org.opencv.ml.CvKNearest.java
org.opencv.ml.CvNormalBayesClassifier.java
org.opencv.ml.CvParamGrid.java
org.opencv.ml.CvRTParams.java
org.opencv.ml.CvRTrees.java
org.opencv.ml.CvSVMParams.java
org.opencv.ml.CvSVM.java
org.opencv.ml.CvStatModel.java
org.opencv.ml.EM.java
org.opencv.ml.Ml.java
org.opencv.objdetect.CascadeClassifier.java
org.opencv.objdetect.HOGDescriptor.java
org.opencv.objdetect.Objdetect.java
org.opencv.photo.Photo.java
org.opencv.utils.Converters.java
org.opencv.video.BackgroundSubtractorMOG2.java
org.opencv.video.BackgroundSubtractorMOG.java
org.opencv.video.BackgroundSubtractor.java
org.opencv.video.KalmanFilter.java
org.opencv.video.Video.java