com.CloudRecognition.CloudReco.java Source code

Java tutorial

Introduction

Here is the source code for com.CloudRecognition.CloudReco.java

Source

/*
 * 
 *  Copyright (c) 2014 Eduardo Corzo
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,MA 02110-1301, USA.
*/
package com.CloudRecognition;

import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Pair;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.qualcomm.vuforia.CameraDevice;
import com.qualcomm.vuforia.ImageTracker;
import com.qualcomm.vuforia.State;
import com.qualcomm.vuforia.TargetFinder;
import com.qualcomm.vuforia.TargetSearchResult;
import com.qualcomm.vuforia.Trackable;
import com.qualcomm.vuforia.Tracker;
import com.qualcomm.vuforia.TrackerManager;
import com.qualcomm.vuforia.Vuforia;
import com.qualcomm.vuforia.SampleApplication.SampleApplicationControl;
import com.qualcomm.vuforia.SampleApplication.SampleApplicationException;
import com.qualcomm.vuforia.SampleApplication.SampleApplicationSession;
import com.example.reconocimientoar.R;
import com.qualcomm.vuforia.ui.SampleAppMenu.SampleAppMenu;
import com.qualcomm.vuforia.ui.SampleAppMenu.SampleAppMenuGroup;
import com.qualcomm.vuforia.ui.SampleAppMenu.SampleAppMenuInterface;

import conexionSiabra.ConexionSiabra;
import conexionSiabra.Oauth;

// The main activity for the CloudReco sample. 
public class CloudReco extends Activity implements SampleApplicationControl, SampleAppMenuInterface {
    private static final String LOGTAG = "Siabra Discover";

    SampleApplicationSession vuforiaAppSession;

    // These codes match the ones defined in TargetFinder in Vuforia.jar
    static final int INIT_SUCCESS = 2;
    static final int INIT_ERROR_NO_NETWORK_CONNECTION = -1;
    static final int INIT_ERROR_SERVICE_NOT_AVAILABLE = -2;
    static final int UPDATE_ERROR_AUTHORIZATION_FAILED = -1;
    static final int UPDATE_ERROR_PROJECT_SUSPENDED = -2;
    static final int UPDATE_ERROR_NO_NETWORK_CONNECTION = -3;
    static final int UPDATE_ERROR_SERVICE_NOT_AVAILABLE = -4;
    static final int UPDATE_ERROR_BAD_FRAME_QUALITY = -5;
    static final int UPDATE_ERROR_UPDATE_SDK = -6;
    static final int UPDATE_ERROR_TIMESTAMP_OUT_OF_RANGE = -7;
    static final int UPDATE_ERROR_REQUEST_TIMEOUT = -8;
    static final int USER_DETECTED = 3;
    static final int HIDE_LOADING_DIALOG = 0;
    static final int SHOW_LOADING_DIALOG = 1;
    static final int HIDE_EVERYTHING = 2;
    // Our OpenGL view:
    private SampleApplicationGLView mGlView;
    // Our renderer:
    private CloudRecoRenderer mRenderer;
    // private GLSurfaceView.Renderer mRenderer;
    private SampleAppMenu mSampleAppMenu;
    private boolean mFlash = false;
    private boolean mContAutofocus = false;
    private boolean mExtendedTracking = false;
    boolean mFinderStarted = false;
    boolean mStopFinderIfStarted = false;
    private View mFlashOptionView;
    // View overlays to be displayed in the Augmented View
    private RelativeLayout mUILayout;
    // Error message handling:
    private int mlastErrorCode = 0;
    private int mInitErrorCode = 0;
    private boolean mFinishActivityOnError;
    // Alert Dialog used to display SDK errors
    private AlertDialog mErrorDialog;
    private GestureDetector mGestureDetector;
    private double mLastErrorTime;
    boolean mIsDroidDevice = false;

    private CargarInformacionHandler loadingDialogHandler = new CargarInformacionHandler(this);
    private static final String kAccessKey = "4632896f497793047720b28ada76626be5eb0ea1";
    private static final String kSecretKey = "5271118083066b1cb03dc59ba7d87fe6152f464c";
    private ConexionSiabra comm;
    private String urlFacebook;
    private String urlTwitter;
    private String urlLinkedin;
    private String urlWebPersonal;
    private String urlWebProfesional;

    // Called when the activity first starts or needs to be recreated after
    // resuming the application or a configuration change.
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(LOGTAG, "onCreate");
        super.onCreate(savedInstanceState);
        comm = new ConexionSiabra(this);
        vuforiaAppSession = new SampleApplicationSession(this);

        startLoadingAnimation();

        vuforiaAppSession.initAR(this, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        // Creates the GestureDetector listener for processing double tap
        mGestureDetector = new GestureDetector(this, new GestureListener());

        mIsDroidDevice = android.os.Build.MODEL.toLowerCase().startsWith("droid");

    }

    // Procesa las pulsaciones realizadas en la pantalla
    private class GestureListener extends GestureDetector.SimpleOnGestureListener {
        // Used to set autofocus one second after a manual focus is triggered
        private final Handler autofocusHandler = new Handler();

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            // Generates a Handler to trigger autofocus
            // after 1 second
            autofocusHandler.postDelayed(new Runnable() {
                public void run() {
                    boolean result = CameraDevice.getInstance()
                            .setFocusMode(CameraDevice.FOCUS_MODE.FOCUS_MODE_TRIGGERAUTO);

                    if (!result)
                        Log.e("SingleTapUp", "Unable to trigger focus");
                }
            }, 1000L);

            return true;
        }
    }

    // Called when the activity will start interacting with the user.
    @Override
    protected void onResume() {
        Log.d(LOGTAG, "onResume");
        super.onResume();

        // This is needed for some Droid devices to force portrait
        if (mIsDroidDevice) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        try {
            vuforiaAppSession.resumeAR();
        } catch (SampleApplicationException e) {
            Log.e(LOGTAG, e.getString());
        }

        // Resume the GL view:
        if (mGlView != null) {
            mGlView.setVisibility(View.VISIBLE);
            mGlView.onResume();
        }

    }

    // Callback for configuration changes the activity handles itself
    @Override
    public void onConfigurationChanged(Configuration config) {
        Log.d(LOGTAG, "onConfigurationChanged");
        super.onConfigurationChanged(config);

        vuforiaAppSession.onConfigurationChanged();
    }

    // Called when the system is about to start resuming a previous activity.
    @Override
    protected void onPause() {
        Log.d(LOGTAG, "onPause");
        super.onPause();

        // Turn off the flash
        if (mFlashOptionView != null && mFlash) {
            // OnCheckedChangeListener is called upon changing the checked state
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                ((Switch) mFlashOptionView).setChecked(false);
            } else {
                ((CheckBox) mFlashOptionView).setChecked(false);
            }
        }

        try {
            vuforiaAppSession.pauseAR();
        } catch (SampleApplicationException e) {
            Log.e(LOGTAG, e.getString());
        }

        // Pauses the OpenGLView
        if (mGlView != null) {
            mGlView.setVisibility(View.INVISIBLE);
            mGlView.onPause();
        }
    }

    // The final call you receive before your activity is destroyed.
    @Override
    protected void onDestroy() {
        Log.d(LOGTAG, "onDestroy");
        super.onDestroy();

        try {
            vuforiaAppSession.stopAR();
        } catch (SampleApplicationException e) {
            Log.e(LOGTAG, e.getString());
        }

        System.gc();
    }

    public void deinitCloudReco() {
        // Get the image tracker:
        TrackerManager trackerManager = TrackerManager.getInstance();
        ImageTracker imageTracker = (ImageTracker) trackerManager.getTracker(ImageTracker.getClassType());
        if (imageTracker == null) {
            Log.e(LOGTAG, "Failed to destroy the tracking data set because the ImageTracker has not"
                    + " been initialized.");
            return;
        }

        // Deinitialize target finder:
        TargetFinder finder = imageTracker.getTargetFinder();
        finder.deinit();
    }

    private void startLoadingAnimation() {
        // Inflates the Overlay Layout to be displayed above the Camera View
        LayoutInflater inflater = LayoutInflater.from(this);
        mUILayout = (RelativeLayout) inflater.inflate(R.layout.camera_overlay, null, false);

        mUILayout.setVisibility(View.VISIBLE);
        mUILayout.setBackgroundColor(Color.BLACK);

        // By default
        loadingDialogHandler.setContenido(mUILayout);

        loadingDialogHandler.mLoadingDialogContainer.setVisibility(View.VISIBLE);

        addContentView(mUILayout, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    }

    // Initializes AR application components.
    private void initApplicationAR() {
        // Create OpenGL ES view:
        int depthSize = 16;
        int stencilSize = 0;
        boolean translucent = Vuforia.requiresAlpha();

        // Initialize the GLView with proper flags
        mGlView = new SampleApplicationGLView(this);
        mGlView.init(translucent, depthSize, stencilSize);

        // Setups the Renderer of the GLView
        mRenderer = new CloudRecoRenderer(vuforiaAppSession, this);
        // mRenderer.setTextures(mTextures);
        mGlView.setRenderer(mRenderer);

    }

    // Returns the error message for each error code
    private String getStatusDescString(int code) {
        if (code == UPDATE_ERROR_AUTHORIZATION_FAILED)
            return getString(R.string.UPDATE_ERROR_AUTHORIZATION_FAILED_DESC);
        if (code == UPDATE_ERROR_PROJECT_SUSPENDED)
            return getString(R.string.UPDATE_ERROR_PROJECT_SUSPENDED_DESC);
        if (code == UPDATE_ERROR_NO_NETWORK_CONNECTION)
            return getString(R.string.UPDATE_ERROR_NO_NETWORK_CONNECTION_DESC);
        if (code == UPDATE_ERROR_SERVICE_NOT_AVAILABLE)
            return getString(R.string.UPDATE_ERROR_SERVICE_NOT_AVAILABLE_DESC);
        if (code == UPDATE_ERROR_UPDATE_SDK)
            return getString(R.string.UPDATE_ERROR_UPDATE_SDK_DESC);
        if (code == UPDATE_ERROR_TIMESTAMP_OUT_OF_RANGE)
            return getString(R.string.UPDATE_ERROR_TIMESTAMP_OUT_OF_RANGE_DESC);
        if (code == UPDATE_ERROR_REQUEST_TIMEOUT)
            return getString(R.string.UPDATE_ERROR_REQUEST_TIMEOUT_DESC);
        if (code == UPDATE_ERROR_BAD_FRAME_QUALITY)
            return getString(R.string.UPDATE_ERROR_BAD_FRAME_QUALITY_DESC);
        else {
            return getString(R.string.UPDATE_ERROR_UNKNOWN_DESC);
        }
    }

    // Returns the error message for each error code
    private String getStatusTitleString(int code) {
        if (code == UPDATE_ERROR_AUTHORIZATION_FAILED)
            return getString(R.string.UPDATE_ERROR_AUTHORIZATION_FAILED_TITLE);
        if (code == UPDATE_ERROR_PROJECT_SUSPENDED)
            return getString(R.string.UPDATE_ERROR_PROJECT_SUSPENDED_TITLE);
        if (code == UPDATE_ERROR_NO_NETWORK_CONNECTION)
            return getString(R.string.UPDATE_ERROR_NO_NETWORK_CONNECTION_TITLE);
        if (code == UPDATE_ERROR_SERVICE_NOT_AVAILABLE)
            return getString(R.string.UPDATE_ERROR_SERVICE_NOT_AVAILABLE_TITLE);
        if (code == UPDATE_ERROR_UPDATE_SDK)
            return getString(R.string.UPDATE_ERROR_UPDATE_SDK_TITLE);
        if (code == UPDATE_ERROR_TIMESTAMP_OUT_OF_RANGE)
            return getString(R.string.UPDATE_ERROR_TIMESTAMP_OUT_OF_RANGE_TITLE);
        if (code == UPDATE_ERROR_REQUEST_TIMEOUT)
            return getString(R.string.UPDATE_ERROR_REQUEST_TIMEOUT_TITLE);
        if (code == UPDATE_ERROR_BAD_FRAME_QUALITY)
            return getString(R.string.UPDATE_ERROR_BAD_FRAME_QUALITY_TITLE);
        else {
            return getString(R.string.UPDATE_ERROR_UNKNOWN_TITLE);
        }
    }

    // Shows error messages as System dialogs
    public void showErrorMessage(int errorCode, double errorTime, boolean finishActivityOnError) {
        if (errorTime < (mLastErrorTime + 5.0) || errorCode == mlastErrorCode)
            return;

        mlastErrorCode = errorCode;
        mFinishActivityOnError = finishActivityOnError;

        runOnUiThread(new Runnable() {
            public void run() {
                if (mErrorDialog != null) {
                    mErrorDialog.dismiss();
                }

                // Generates an Alert Dialog to show the error message
                AlertDialog.Builder builder = new AlertDialog.Builder(CloudReco.this);
                builder.setMessage(getStatusDescString(CloudReco.this.mlastErrorCode))
                        .setTitle(getStatusTitleString(CloudReco.this.mlastErrorCode)).setCancelable(false)
                        .setIcon(0)
                        .setPositiveButton(getString(R.string.button_OK), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                if (mFinishActivityOnError) {
                                    finish();
                                } else {
                                    dialog.dismiss();
                                }
                            }
                        });

                mErrorDialog = builder.create();
                mErrorDialog.show();
            }
        });
    }

    public void startFinderIfStopped() {

        if (!mFinderStarted) {
            Log.wtf("Se", "ha perdido el objeto");//COMIENZA EL ESCANER CUANDO NO SE PIERDE EL OBJETO ESCANEADO
            loadingDialogHandler.sendEmptyMessage(HIDE_EVERYTHING);//
            mFinderStarted = true;

            // Get the image tracker:
            TrackerManager trackerManager = TrackerManager.getInstance();
            ImageTracker imageTracker = (ImageTracker) trackerManager.getTracker(ImageTracker.getClassType());

            // Initialize target finder:
            TargetFinder targetFinder = imageTracker.getTargetFinder();

            targetFinder.clearTrackables();
            targetFinder.startRecognition();
        }
    }

    public void stopFinderIfStarted() {
        if (mFinderStarted) {
            mFinderStarted = false;

            // Get the image tracker:
            TrackerManager trackerManager = TrackerManager.getInstance();
            ImageTracker imageTracker = (ImageTracker) trackerManager.getTracker(ImageTracker.getClassType());

            // Initialize target finder:
            TargetFinder targetFinder = imageTracker.getTargetFinder();

            targetFinder.stop();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Process the Gestures
        if (mSampleAppMenu != null && mSampleAppMenu.processEvent(event))
            return true;

        return mGestureDetector.onTouchEvent(event);
    }

    @Override
    public boolean doLoadTrackersData() {
        Log.d(LOGTAG, "initCloudReco");

        // Get the image tracker:
        TrackerManager trackerManager = TrackerManager.getInstance();
        ImageTracker imageTracker = (ImageTracker) trackerManager.getTracker(ImageTracker.getClassType());

        // Initialize target finder:
        TargetFinder targetFinder = imageTracker.getTargetFinder();

        // Start initialization:
        if (targetFinder.startInit(kAccessKey, kSecretKey)) {
            targetFinder.waitUntilInitFinished();
        }

        int resultCode = targetFinder.getInitState();
        if (resultCode != TargetFinder.INIT_SUCCESS) {
            if (resultCode == TargetFinder.INIT_ERROR_NO_NETWORK_CONNECTION) {
                mInitErrorCode = UPDATE_ERROR_NO_NETWORK_CONNECTION;
            } else {
                mInitErrorCode = UPDATE_ERROR_SERVICE_NOT_AVAILABLE;
            }

            Log.e(LOGTAG, "Failed to initialize target finder.");
            return false;
        }

        return true;
    }

    @Override
    public boolean doUnloadTrackersData() {
        return true;
    }

    @Override
    public void onInitARDone(SampleApplicationException exception) {

        if (exception == null) {
            initApplicationAR();

            // Now add the GL surface view. It is important
            // that the OpenGL ES surface view gets added
            // BEFORE the camera is started and video
            // background is configured.
            addContentView(mGlView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

            // Start the camera:
            try {
                vuforiaAppSession.startAR(CameraDevice.CAMERA.CAMERA_DEFAULT);
            } catch (SampleApplicationException e) {
                Log.e(LOGTAG, e.getString());
            }

            boolean result = CameraDevice.getInstance()
                    .setFocusMode(CameraDevice.FOCUS_MODE.FOCUS_MODE_CONTINUOUSAUTO);

            if (result)
                mContAutofocus = true;
            else
                Log.e(LOGTAG, "Unable to enable continuous autofocus");

            mUILayout.bringToFront();

            // Hides the Loading Dialog
            loadingDialogHandler.sendEmptyMessage(HIDE_LOADING_DIALOG);

            mUILayout.setBackgroundColor(Color.TRANSPARENT);

            mSampleAppMenu = new SampleAppMenu(this, this, "SIABRA Discover", mGlView, mUILayout, null);
            setSampleAppMenuSettings();

        } else {
            Log.e(LOGTAG, exception.getString());
            if (mInitErrorCode != 0) {
                showErrorMessage(mInitErrorCode, 10, true);
            } else {
                finish();
            }
        }
    }

    /*
     * FUNCION QUE ME DETECTA LAS IMAGENES
     * AQUI OBTENGO EL NOMBRE DE LA IMAGEN RECONOCIDA
     */
    @Override
    public void onQCARUpdate(State state) {
        // Get the tracker manager:
        TrackerManager trackerManager = TrackerManager.getInstance();

        // Get the image tracker:
        ImageTracker imageTracker = (ImageTracker) trackerManager.getTracker(ImageTracker.getClassType());

        // Get the target finder:
        TargetFinder finder = imageTracker.getTargetFinder();

        // Check if there are new results available:
        final int statusCode = finder.updateSearchResults();

        // Show a message if we encountered an error:
        if (statusCode < 0) {

            boolean closeAppAfterError = (statusCode == UPDATE_ERROR_NO_NETWORK_CONNECTION
                    || statusCode == UPDATE_ERROR_SERVICE_NOT_AVAILABLE);

            showErrorMessage(statusCode, state.getFrame().getTimeStamp(), closeAppAfterError);

        } else if (statusCode == TargetFinder.UPDATE_RESULTS_AVAILABLE) {

            // Process new search results
            if (finder.getResultCount() > 0) {
                TargetSearchResult result = finder.getResult(0);
                Message msg = new Message();
                JSONObject json = comm.getInformacionOtroUsuario(result.getTargetName());
                Bundle data = conversor(json);

                msg.setData(data);
                msg.what = USER_DETECTED;
                loadingDialogHandler.sendMessage(msg);

                // Check if this target is suitable for tracking:
                if (result.getTrackingRating() > 0) {
                    Trackable trackable = finder.enableTracking(result);

                    if (mExtendedTracking)
                        trackable.startExtendedTracking();
                }
            }
        }

    }

    /*
     * Me convierte un objeto json en un objeto Bundle
     * Ademas actualiza los valores de las urls que tiene el objeto json
     */
    private Bundle conversor(JSONObject json) {
        Bundle resultado = new Bundle();
        Iterator<String> keys = json.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            try {
                resultado.putString(key, json.getString(key));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        urlFacebook = resultado.getString("facebook");
        urlTwitter = resultado.getString("twitter");
        urlLinkedin = resultado.getString("linkedin");
        urlWebPersonal = resultado.getString("webPersonal");
        urlWebProfesional = resultado.getString("webProfesional");
        return resultado;
    }

    /*
     * Al pulsar el boton de facebook me lleva a su pagina web
     */
    public void goToFacebook(View view) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(urlFacebook));
        this.startActivity(intent);
    }

    /*
     * Al pulsar el boton de Twitter    me lleva a su pagina web
     */
    public void goToTwitter(View view) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(urlTwitter));
        this.startActivity(intent);
    }

    /*
     * Al pulsar el boton de Linkedin me lleva a su pagina web
     */
    public void goToLinkedin(View view) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(urlLinkedin));
        this.startActivity(intent);
    }

    /*
     * Al pulsar el boton de WebPersonal me lleva a su pagina web
     */
    public void goToWebPersonal(View view) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(urlWebPersonal));
        this.startActivity(intent);
    }

    /*
     * Al pulsar el boton de WebProfesional me lleva a su pagina web
     */
    public void goToWebProfesional(View view) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Log.wtf("direccion", urlWebProfesional);
        intent.setData(Uri.parse(urlWebProfesional));
        this.startActivity(intent);
    }

    @Override
    public boolean doInitTrackers() {
        TrackerManager tManager = TrackerManager.getInstance();
        Tracker tracker;

        // Indicate if the trackers were initialized correctly
        boolean result = true;

        tracker = tManager.initTracker(ImageTracker.getClassType());
        if (tracker == null) {
            Log.e(LOGTAG, "Tracker not initialized. Tracker already initialized or the camera is already started");
            result = false;
        } else {
            Log.i(LOGTAG, "Tracker successfully initialized");
        }

        return result;
    }

    @Override
    public boolean doStartTrackers() {
        // Indicate if the trackers were started correctly
        boolean result = true;

        // Start the tracker:
        TrackerManager trackerManager = TrackerManager.getInstance();
        ImageTracker imageTracker = (ImageTracker) trackerManager.getTracker(ImageTracker.getClassType());
        imageTracker.start();

        // Start cloud based recognition if we are in scanning mode:
        TargetFinder targetFinder = imageTracker.getTargetFinder();
        targetFinder.startRecognition();
        mFinderStarted = true;

        return result;
    }

    @Override
    public boolean doStopTrackers() {
        // Indicate if the trackers were stopped correctly
        boolean result = true;

        TrackerManager trackerManager = TrackerManager.getInstance();
        ImageTracker imageTracker = (ImageTracker) trackerManager.getTracker(ImageTracker.getClassType());

        if (imageTracker != null) {
            imageTracker.stop();

            // Stop cloud based recognition:
            TargetFinder targetFinder = imageTracker.getTargetFinder();
            targetFinder.stop();
            mFinderStarted = false;

            // Clears the trackables
            targetFinder.clearTrackables();
        } else {
            result = false;
        }

        return result;
    }

    @Override
    public boolean doDeinitTrackers() {
        // Indicate if the trackers were deinitialized correctly
        boolean result = true;

        TrackerManager tManager = TrackerManager.getInstance();
        tManager.deinitTracker(ImageTracker.getClassType());

        return result;
    }

    final public static int CMD_BACK = -1;
    final public static int CMD_EXTENDED_TRACKING = 1;
    final public static int CMD_AUTOFOCUS = 2;
    final public static int CMD_FLASH = 3;
    final public static int CMD_CAMERA_FRONT = 4;
    final public static int CMD_CAMERA_REAR = 5;
    final public static int CMD_SESION = 6;

    // This method sets the menu's settings
    private void setSampleAppMenuSettings() {
        SampleAppMenuGroup group;
        group = mSampleAppMenu.addGroup("", false);
        group.addTextItem(getString(R.string.close_app), -1);

        group = mSampleAppMenu.addGroup("", false);
        group.addTextItem(getString(R.string.menu_back), 6);

        group = mSampleAppMenu.addGroup("", true);
        group.addSelectionItem(getString(R.string.menu_extended_tracking), CMD_EXTENDED_TRACKING, false);
        group.addSelectionItem(getString(R.string.menu_contAutofocus), CMD_AUTOFOCUS, mContAutofocus);
        mFlashOptionView = group.addSelectionItem(getString(R.string.menu_flash), CMD_FLASH, false);

        CameraInfo ci = new CameraInfo();
        boolean deviceHasFrontCamera = false;
        boolean deviceHasBackCamera = false;
        for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
            Camera.getCameraInfo(i, ci);
            if (ci.facing == CameraInfo.CAMERA_FACING_FRONT)
                deviceHasFrontCamera = true;
            else if (ci.facing == CameraInfo.CAMERA_FACING_BACK)
                deviceHasBackCamera = true;
        }

        if (deviceHasBackCamera && deviceHasFrontCamera) {
            group = mSampleAppMenu.addGroup(getString(R.string.menu_camera), true);
            group.addRadioItem(getString(R.string.menu_camera_front), CMD_CAMERA_FRONT, false);
            group.addRadioItem(getString(R.string.menu_camera_back), CMD_CAMERA_REAR, true);
        }

        mSampleAppMenu.attachMenu();
    }

    @Override
    public boolean menuProcess(int command) {
        boolean result = true;

        switch (command) {
        case CMD_BACK:
            finish();
            break;

        case CMD_SESION:
            Log.wtf("HEY", "HO");
            comm.borrarBaseDeDatos();
            //Quizas haya que crear un nuevo comm   
            finish();
            break;

        case CMD_FLASH:
            result = CameraDevice.getInstance().setFlashTorchMode(!mFlash);

            if (result) {
                mFlash = !mFlash;
            } else {
                showToast(getString(mFlash ? R.string.menu_flash_error_off : R.string.menu_flash_error_on));
                Log.e(LOGTAG, getString(mFlash ? R.string.menu_flash_error_off : R.string.menu_flash_error_on));
            }
            break;

        case CMD_AUTOFOCUS:

            if (mContAutofocus) {
                result = CameraDevice.getInstance().setFocusMode(CameraDevice.FOCUS_MODE.FOCUS_MODE_NORMAL);

                if (result) {
                    mContAutofocus = false;
                } else {
                    showToast(getString(R.string.menu_contAutofocus_error_off));
                    Log.e(LOGTAG, getString(R.string.menu_contAutofocus_error_off));
                }
            } else {
                result = CameraDevice.getInstance().setFocusMode(CameraDevice.FOCUS_MODE.FOCUS_MODE_CONTINUOUSAUTO);

                if (result) {
                    mContAutofocus = true;
                } else {
                    showToast(getString(R.string.menu_contAutofocus_error_on));
                    Log.e(LOGTAG, getString(R.string.menu_contAutofocus_error_on));
                }
            }

            break;

        case CMD_EXTENDED_TRACKING:
            TrackerManager trackerManager = TrackerManager.getInstance();
            ImageTracker imageTracker = (ImageTracker) trackerManager.getTracker(ImageTracker.getClassType());

            TargetFinder targetFinder = imageTracker.getTargetFinder();

            if (targetFinder.getNumImageTargets() == 0) {
                result = false;
                showToast(getString(R.string.menu_extended_tracking_no_targets));
            }

            for (int tIdx = 0; tIdx < targetFinder.getNumImageTargets(); tIdx++) {
                Trackable trackable = targetFinder.getImageTarget(tIdx);

                if (!mExtendedTracking) {
                    if (!trackable.startExtendedTracking()) {
                        Log.e(LOGTAG, "Failed to start extended tracking target");
                        result = false;
                    } else {
                        Log.d(LOGTAG, "Successfully started extended tracking target");
                    }
                } else {
                    if (!trackable.stopExtendedTracking()) {
                        Log.e(LOGTAG, "Failed to stop extended tracking target");
                        result = false;
                    } else {
                        Log.d(LOGTAG, "Successfully started extended tracking target");
                    }
                }
            }

            if (result)
                mExtendedTracking = !mExtendedTracking;

            break;

        case CMD_CAMERA_FRONT:
        case CMD_CAMERA_REAR:
            // Turn off the flash
            if (mFlashOptionView != null && mFlash) {
                // OnCheckedChangeListener is called upon changing the checked state
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    ((Switch) mFlashOptionView).setChecked(false);
                } else {
                    ((CheckBox) mFlashOptionView).setChecked(false);
                }
            }

            doStopTrackers();
            CameraDevice.getInstance().stop();
            CameraDevice.getInstance().deinit();
            try {
                vuforiaAppSession.startAR(command == CMD_CAMERA_FRONT ? CameraDevice.CAMERA.CAMERA_FRONT
                        : CameraDevice.CAMERA.CAMERA_BACK);
            } catch (SampleApplicationException e) {
                showToast(e.getString());
                Log.e(LOGTAG, e.getString());
                result = false;
            }
            doStartTrackers();
            break;

        }

        return result;
    }

    private void showToast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }

}