예제 #1
0
 /**
  * This instantiates the GL10, GL11 and GL20 instances. Includes the check for certain devices
  * that pretend to support GL11 but f**k up vertex buffer objects. This includes the pixelflinger
  * which segfaults when buffers are deleted as well as the Motorola CLIQ and the Samsung Behold
  * II.
  *
  * @param gl
  */
 private void setupGL(javax.microedition.khronos.opengles.GL10 gl) {
   if (gl10 != null || gl20 != null) return;
   if (view instanceof GLSurfaceView20) {
     gl20 = new AndroidGL20();
     this.gl = gl20;
   } else {
     gl10 = new AndroidGL10(gl);
     this.gl = gl10;
     if (gl instanceof javax.microedition.khronos.opengles.GL11) {
       String renderer = gl.glGetString(GL10.GL_RENDERER);
       if (renderer != null) { // silly GT-I7500
         if (!renderer.toLowerCase().contains("pixelflinger")
             && !(android.os.Build.MODEL.equals("MB200")
                 || android.os.Build.MODEL.equals("MB220")
                 || android.os.Build.MODEL.contains("Behold"))) {
           gl11 = new AndroidGL11((javax.microedition.khronos.opengles.GL11) gl);
           gl10 = gl11;
         }
       }
     }
   }
   this.glu = new AndroidGLU();
   Gdx.gl = this.gl;
   Gdx.gl10 = gl10;
   Gdx.gl11 = gl11;
   Gdx.gl20 = gl20;
   Gdx.glu = glu;
   Gdx.app.log("AndroidGraphics", "OGL renderer: " + gl.glGetString(GL10.GL_RENDERER));
   Gdx.app.log("AndroidGraphics", "OGL vendor: " + gl.glGetString(GL10.GL_VENDOR));
   Gdx.app.log("AndroidGraphics", "OGL version: " + gl.glGetString(GL10.GL_VERSION));
   Gdx.app.log("AndroidGraphics", "OGL extensions: " + gl.glGetString(GL10.GL_EXTENSIONS));
 }
예제 #2
0
  // 判断当前设备是否是模拟器。如果返回TRUE,则当前是模拟器,不是返回FALSE
  public boolean isEmulator(Context context) {
    try {
      TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
      String imei = tm.getDeviceId();
      if (imei != null && imei.equals("000000000000000")) {
        return true;
      }
      return (Build.MODEL.equals("sdk")) || (Build.MODEL.equals("google_sdk"));
    } catch (Exception ioe) {

    }
    return false;
  }
예제 #3
0
  private void setVideoCover(double time) {

    ivDone.setEnabled(true);
    ivUndo.setEnabled(true);
    flCoverSetted.setVisibility(View.VISIBLE);
    ivCover.setVisibility(View.GONE);
    videoCoverTime = time;
    thumbBmp =
        mMediaPlayer.videScreenCapture(
            videoCoverTime,
            EffectType.EFFECT_VIDEO_DEFAULT_WIDTH,
            EffectType.EFFECT_VIDEO_DEFAULT_WIDTH);
    if (android.os.Build.MODEL.equalsIgnoreCase("GT-N7100")
        || android.os.Build.MODEL.equalsIgnoreCase("GT-I9300")
        || android.os.Build.MODEL.equals("GT-I9220")
        || android.os.Build.MODEL.startsWith("GT-I9100")) {
      Mp4Info info = new Mp4Info(curVideoPath);
      thumbBmp = ZGraphics.rotate(thumbBmp, info.angle, true);
    }
    curAngle = mMediaPlayer.getCurrentOrientation();
    Log.d(TAG, "setVideoCover time = " + time + " curAngle = " + curAngle);
    Bitmap bmp = BitmapUtils.rotate(thumbBmp, (360 - curAngle) % 360, true);
    ivCoverSetted.setImageBitmap(bmp);

    OperateNote operate = new OperateNote();
    operate.operateType = OPERATE_COVER;
    operate.videoPath = curVideoPath;
    operate.angle = curAngle;
    operate.coverTime = videoCoverTime;
    operateNotesList.add(operate);
  }
예제 #4
0
  public static boolean isEmulator(Context context) {
    boolean ret = false;
    try {
      TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
      String imei = tm.getDeviceId();
      if (imei != null && imei.equals("000000000000000")) {
        ret = true;
      }
      ret = (Build.MODEL.equals("sdk")) || (Build.MODEL.equals("google_sdk"));
      if (!ret) {
        ret = isBlueStacks();
      }
      if (!ret) {
        ret = isGenymotion();
      }
    } catch (Exception ioe) {

    }
    return ret;
  }
예제 #5
0
 public boolean IsXperiaPlay() {
   return android.os.Build.MODEL.equals("R800a")
       || android.os.Build.MODEL.equals("R800i")
       || android.os.Build.MODEL.equals("R800x")
       || android.os.Build.MODEL.equals("R800at")
       || android.os.Build.MODEL.equals("SO-01D")
       || android.os.Build.MODEL.equals("zeus");
 }
  @Override
  public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ConnectivityManager connMan = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    view = (TextView) findViewById(R.id.currentIpAddr);
    button = (Button) findViewById(R.id.firstButton);

    this.registerReceiver(this.mConn, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    if (connMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {
      WifiManager wifiMan = (WifiManager) getSystemService(WIFI_SERVICE);
      start(wifiMan.getConnectionInfo().getSSID().toString());
    } else if (Build.MODEL.equals("sdk")) {
      start("sdk"); // Android emulator
    } else {
      view.setText("Not connected to Wi-Fi");
      button.setEnabled(Boolean.FALSE);
    }
  }
예제 #7
0
  public boolean StartEngine() {
    PowerManager pm = (PowerManager) getUIContext().getSystemService(Context.POWER_SERVICE);
    if (wl == null) {
      if (!PreferenceManager.getDefaultSharedPreferences(getUIContext())
          .contains(org.ruby.client.ui.Settings.PREF_KEEPON)) {
        Editor edit = PreferenceManager.getDefaultSharedPreferences(getUIContext()).edit();

        edit.putBoolean(
            org.ruby.client.ui.Settings.PREF_KEEPON,
            Build.MODEL.equals("Nexus One")
                || Build.MODEL.equals("Nexus S")
                || Build.MODEL.equals("Archos5")
                || Build.MODEL.equals("ADR6300")
                || Build.MODEL.equals("PC36100")
                || Build.MODEL.equals("HTC Desire")
                || Build.MODEL.equals("HTC Incredible S")
                || Build.MODEL.equals("HTC Wildfire"));
        edit.commit();
      }
      wl = new PowerManager.WakeLock[LINES];
      pwl = new PowerManager.WakeLock[LINES];
    }
    pref = ChangeAccount.getPref(Receiver.mContext);

    uas = new UserAgent[LINES];
    ras = new RegisterAgent[LINES];
    kas = new KeepAliveSip[LINES];
    lastmsgs = new String[LINES];
    sip_providers = new SipProvider[LINES];
    user_profiles = new UserAgentProfile[LINES];
    user_profiles[0] = getUserAgentProfile("");
    for (int i = 1; i < LINES; i++) user_profiles[1] = getUserAgentProfile("" + i);

    SipStack.init(null);
    int i = 0;
    for (UserAgentProfile user_profile : user_profiles) {
      if (wl[i] == null) {
        wl[i] = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Ruby.RubyEngine");
        if (PreferenceManager.getDefaultSharedPreferences(getUIContext())
            .getBoolean(
                org.ruby.client.ui.Settings.PREF_KEEPON,
                org.ruby.client.ui.Settings.DEFAULT_KEEPON))
          pwl[i] =
              pm.newWakeLock(
                  PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
                  "Ruby.RubyEngine");
      }

      try {
        SipStack.debug_level = 0;
        //			SipStack.log_path = "/data/data/org.Rubyent";
        SipStack.max_retransmission_timeout = 4000;
        SipStack.default_transport_protocols = new String[1];
        SipStack.default_transport_protocols[0] =
            PreferenceManager.getDefaultSharedPreferences(getUIContext())
                .getString(
                    Settings.PREF_PROTOCOL + (i != 0 ? i : ""),
                    user_profile.realm.equals(Settings.DEFAULT_SERVER) ? "tcp" : "udp");

        String version = "Ruby/" + Ruby.getVersion() + "/" + Build.MODEL;
        SipStack.ua_info = version;
        SipStack.server_info = version;

        IpAddress.setLocalIpAddress();
        sip_providers[i] = new SipProvider(IpAddress.localIpAddress, 0);
        user_profile.contact_url = getContactURL(user_profile.username, sip_providers[i]);

        if (user_profile.from_url.indexOf("@") < 0) {
          user_profile.from_url += "@" + user_profile.realm;
        }

        CheckEngine();

        // added by mandrajg
        String icsi = null;
        if (user_profile.mmtel == true) {
          icsi = "\"urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel\"";
        }

        uas[i] = ua = new UserAgent(sip_providers[i], user_profile);
        ras[i] =
            new RegisterAgent(
                sip_providers[i],
                user_profile.from_url, // modified
                user_profile.contact_url,
                user_profile.username,
                user_profile.realm,
                user_profile.passwd,
                this,
                user_profile,
                user_profile.qvalue,
                icsi,
                user_profile.pub); // added by mandrajg
        kas[i] = new KeepAliveSip(sip_providers[i], 100000);
      } catch (Exception E) {
      }
      i++;
    }
    register();
    listen();

    return true;
  }
예제 #8
0
  @Override
  @SuppressLint("SetJavaScriptEnabled")
  protected void onCreate(Bundle savedInstanceState) {
    // on MB612, the search and share icon is so dark ...
    if (Build.MODEL.equals("MB612")) {
      setTheme(android.R.style.Theme_Light_NoTitleBar);
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chapter);
    findViewById(R.id.book).setOnClickListener(this);
    findViewById(R.id.chapter).setOnClickListener(this);
    findViewById(R.id.search).setOnClickListener(this);
    findViewById(R.id.version).setOnClickListener(this);
    findViewById(R.id.share).setOnClickListener(this);
    findViewById(R.id.items).setOnClickListener(this);

    adapter =
        new ArrayAdapter<String>(this, R.layout.grid) {
          private LayoutInflater inflater =
              (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

          @Override
          public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            ToggleButton grid = null;
            if (view == null) {
              view = inflater.inflate(R.layout.grid, null);
            }
            grid = (ToggleButton) view.findViewById(R.id.text1);
            grid.setTextOn(getItem(position));
            grid.setTextOff(getItem(position));
            grid.setChecked(getItem(position).equals(selected));
            grid.setVisibility(getItem(position).equals("") ? View.INVISIBLE : View.VISIBLE);
            return view;
          }
        };

    gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(adapter);
    gridview.setVisibility(View.GONE);
    gridview.setOnItemClickListener(this);

    setGestureDetector();
    webview = (WebView) findViewById(R.id.webview);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setSupportZoom(true);
    webview.getSettings().setBuiltInZoomControls(true);
    webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    webview.addJavascriptInterface(
        new Object() {
          @SuppressWarnings("unused")
          public void setVerse(String string) {
            synchronized (verseLock) {
              verse = string;
              Log.d(TAG, "verse from javascript: " + verse);
              verseLock.notifyAll();
            }
          }

          @SuppressWarnings({"unused", "deprecation"})
          public void setCopyText(String text) {
            if (!text.equals("")) {
              copytext =
                  bible
                          .getVersionFullname(version)
                          .replace("(" + getString(R.string.demo) + ")", "")
                      + " ";
              copytext +=
                  bible.get(Bible.TYPE.HUMAN, bible.getPosition(Bible.TYPE.OSIS, book))
                      + " "
                      + chapter
                      + ":"
                      + text;
              ((android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE))
                  .setText(copytext);
              Log.d(TAG, "copy from javascript: " + copytext);
            } else {
              copytext = "";
            }
            handler.sendEmptyMessage(COPYTEXT);
          }
        },
        "android");
    setZoomButtonsController(webview);

    osis = PreferenceManager.getDefaultSharedPreferences(this).getString("osis", "null");
    uri =
        Provider.CONTENT_URI_CHAPTER.buildUpon().appendEncodedPath(osis).fragment(version).build();

    setIntentData();
    int color = 0x6633B5E5;
    Integer mHighlightColor =
        (Integer) Bible.getField(findViewById(R.id.version), TextView.class, "mHighlightColor");
    if (mHighlightColor != null) {
      color = mHighlightColor.intValue();
    }
    background =
        String.format(
            "background: rgba(%d, %d, %d, %.2f);",
            (color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF, (color >>> 24) / 255.0);
    Log.d(TAG, "onCreate");
    hasIntentData = true;
    font =
        new File(
            new File(
                new File(
                    new File(
                        new File(Environment.getExternalStorageDirectory(), "Android"), "data"),
                    getPackageName()),
                "files"),
            "custom.ttf");
  }
예제 #9
0
/** @author Andreas Schildbach */
public final class ScanActivity extends Activity implements SurfaceHolder.Callback {
  public static final String INTENT_EXTRA_RESULT = "result";

  private static final long VIBRATE_DURATION = 50L;
  private static final long AUTO_FOCUS_INTERVAL_MS = 2500L;

  private final CameraManager cameraManager = new CameraManager();
  private ScannerView scannerView;
  private SurfaceHolder surfaceHolder;
  private Vibrator vibrator;
  private HandlerThread cameraThread;
  private Handler cameraHandler;

  private static final int DIALOG_CAMERA_PROBLEM = 0;

  private static boolean DISABLE_CONTINUOUS_AUTOFOCUS =
      Build.MODEL.equals("GT-I9100") // Galaxy S2
          || Build.MODEL.equals("SGH-T989") // Galaxy S2
          || Build.MODEL.equals("SGH-T989D") // Galaxy S2 X
          || Build.MODEL.equals("SAMSUNG-SGH-I727") // Galaxy S2 Skyrocket
          || Build.MODEL.equals("GT-I9300") // Galaxy S3
          || Build.MODEL.equals("GT-N7000"); // Galaxy Note

  private static final Logger log = LoggerFactory.getLogger(ScanActivity.class);

  @Override
  public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

    setContentView(R.layout.scan_activity);

    scannerView = (ScannerView) findViewById(R.id.scan_activity_mask);
  }

  @Override
  protected void onResume() {
    super.onResume();

    cameraThread = new HandlerThread("cameraThread", Process.THREAD_PRIORITY_BACKGROUND);
    cameraThread.start();
    cameraHandler = new Handler(cameraThread.getLooper());

    final SurfaceView surfaceView = (SurfaceView) findViewById(R.id.scan_activity_preview);
    surfaceHolder = surfaceView.getHolder();
    surfaceHolder.addCallback(this);
    surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
  }

  @Override
  public void surfaceCreated(final SurfaceHolder holder) {
    cameraHandler.post(openRunnable);
  }

  @Override
  public void surfaceDestroyed(final SurfaceHolder holder) {}

  @Override
  public void surfaceChanged(
      final SurfaceHolder holder, final int format, final int width, final int height) {}

  @Override
  protected void onPause() {
    cameraHandler.post(closeRunnable);

    surfaceHolder.removeCallback(this);

    super.onPause();
  }

  @Override
  public void onBackPressed() {
    setResult(RESULT_CANCELED);
    finish();
  }

  @Override
  public boolean onKeyDown(final int keyCode, final KeyEvent event) {
    switch (keyCode) {
      case KeyEvent.KEYCODE_FOCUS:
      case KeyEvent.KEYCODE_CAMERA:
        // don't launch camera app
        return true;
      case KeyEvent.KEYCODE_VOLUME_DOWN:
      case KeyEvent.KEYCODE_VOLUME_UP:
        cameraHandler.post(
            new Runnable() {
              @Override
              public void run() {
                cameraManager.setTorch(keyCode == KeyEvent.KEYCODE_VOLUME_UP);
              }
            });
        return true;
    }

    return super.onKeyDown(keyCode, event);
  }

  public void handleResult(
      final Result scanResult, final Bitmap thumbnailImage, final float thumbnailScaleFactor) {
    vibrator.vibrate(VIBRATE_DURATION);

    // superimpose dots to highlight the key features of the qr code
    final ResultPoint[] points = scanResult.getResultPoints();
    if (points != null && points.length > 0) {
      final Paint paint = new Paint();
      paint.setColor(getResources().getColor(R.color.scan_result_dots));
      paint.setStrokeWidth(10.0f);

      final Canvas canvas = new Canvas(thumbnailImage);
      canvas.scale(thumbnailScaleFactor, thumbnailScaleFactor);
      for (final ResultPoint point : points) canvas.drawPoint(point.getX(), point.getY(), paint);
    }

    scannerView.drawResultBitmap(thumbnailImage);

    final Intent result = new Intent();
    result.putExtra(INTENT_EXTRA_RESULT, scanResult.getText());
    setResult(RESULT_OK, result);

    // delayed finish
    new Handler()
        .post(
            new Runnable() {
              @Override
              public void run() {
                finish();
              }
            });
  }

  private final Runnable openRunnable =
      new Runnable() {
        @Override
        public void run() {
          try {
            final Camera camera = cameraManager.open(surfaceHolder, !DISABLE_CONTINUOUS_AUTOFOCUS);

            final Rect framingRect = cameraManager.getFrame();
            final Rect framingRectInPreview = cameraManager.getFramePreview();

            runOnUiThread(
                new Runnable() {
                  @Override
                  public void run() {
                    scannerView.setFraming(framingRect, framingRectInPreview);
                  }
                });

            final String focusMode = camera.getParameters().getFocusMode();
            final boolean nonContinuousAutoFocus =
                Camera.Parameters.FOCUS_MODE_AUTO.equals(focusMode)
                    || Camera.Parameters.FOCUS_MODE_MACRO.equals(focusMode);

            if (nonContinuousAutoFocus) cameraHandler.post(new AutoFocusRunnable(camera));

            cameraHandler.post(fetchAndDecodeRunnable);
          } catch (final IOException x) {
            log.info("problem opening camera", x);
            showDialog(DIALOG_CAMERA_PROBLEM);
          } catch (final RuntimeException x) {
            log.info("problem opening camera", x);
            showDialog(DIALOG_CAMERA_PROBLEM);
          }
        }
      };

  private final Runnable closeRunnable =
      new Runnable() {
        @Override
        public void run() {
          cameraManager.close();

          // cancel background thread
          cameraHandler.removeCallbacksAndMessages(null);
          cameraThread.quit();
        }
      };

  private final class AutoFocusRunnable implements Runnable {
    private final Camera camera;

    public AutoFocusRunnable(final Camera camera) {
      this.camera = camera;
    }

    @Override
    public void run() {
      camera.autoFocus(
          new Camera.AutoFocusCallback() {
            @Override
            public void onAutoFocus(final boolean success, final Camera camera) {
              // schedule again
              cameraHandler.postDelayed(AutoFocusRunnable.this, AUTO_FOCUS_INTERVAL_MS);
            }
          });
    }
  }

  private final Runnable fetchAndDecodeRunnable =
      new Runnable() {
        private final QRCodeReader reader = new QRCodeReader();
        private final Map<DecodeHintType, Object> hints =
            new EnumMap<DecodeHintType, Object>(DecodeHintType.class);

        @Override
        public void run() {
          cameraManager.requestPreviewFrame(
              new PreviewCallback() {
                @Override
                public void onPreviewFrame(final byte[] data, final Camera camera) {
                  decode(data);
                }
              });
        }

        private void decode(final byte[] data) {
          final PlanarYUVLuminanceSource source = cameraManager.buildLuminanceSource(data);
          final BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

          try {
            hints.put(
                DecodeHintType.NEED_RESULT_POINT_CALLBACK,
                new ResultPointCallback() {
                  @Override
                  public void foundPossibleResultPoint(final ResultPoint dot) {
                    runOnUiThread(
                        new Runnable() {
                          @Override
                          public void run() {
                            scannerView.addDot(dot);
                          }
                        });
                  }
                });
            final Result scanResult = reader.decode(bitmap, hints);

            final int thumbnailWidth = source.getThumbnailWidth();
            final int thumbnailHeight = source.getThumbnailHeight();
            final float thumbnailScaleFactor = (float) thumbnailWidth / source.getWidth();

            final Bitmap thumbnailImage =
                Bitmap.createBitmap(thumbnailWidth, thumbnailHeight, Bitmap.Config.ARGB_8888);
            thumbnailImage.setPixels(
                source.renderThumbnail(), 0, thumbnailWidth, 0, 0, thumbnailWidth, thumbnailHeight);

            runOnUiThread(
                new Runnable() {
                  @Override
                  public void run() {
                    handleResult(scanResult, thumbnailImage, thumbnailScaleFactor);
                  }
                });
          } catch (final ReaderException x) {
            // retry
            cameraHandler.post(fetchAndDecodeRunnable);
          } finally {
            reader.reset();
          }
        }
      };

  @Override
  protected Dialog onCreateDialog(final int id) {
    if (id == DIALOG_CAMERA_PROBLEM) {
      final DialogBuilder dialog =
          DialogBuilder.warn(this, R.string.scan_camera_problem_dialog_title);
      dialog.setMessage(R.string.scan_camera_problem_dialog_message);
      dialog.singleDismissButton(
          new OnClickListener() {
            @Override
            public void onClick(final DialogInterface dialog, final int which) {
              finish();
            }
          });
      dialog.setOnCancelListener(
          new OnCancelListener() {
            @Override
            public void onCancel(final DialogInterface dialog) {
              finish();
            }
          });

      return dialog.create();
    } else {
      throw new IllegalArgumentException();
    }
  }
}
  protected boolean initializeCamera(int width, int height) {
    Log.d(TAG, "Initialize java camera");
    boolean result = true;
    synchronized (this) {
      mCamera = null;

      if (mCameraIndex == CAMERA_ID_ANY) {
        Log.d(TAG, "Trying to open camera with old open()");
        try {
          mCamera = Camera.open();
        } catch (Exception e) {
          Log.e(
              TAG,
              "Camera is not available (in use or does not exist): " + e.getLocalizedMessage());
        }

        if (mCamera == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
          boolean connected = false;
          for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); ++camIdx) {
            Log.d(TAG, "Trying to open camera with new open(" + Integer.valueOf(camIdx) + ")");
            try {
              mCamera = Camera.open(camIdx);
              connected = true;
            } catch (RuntimeException e) {
              Log.e(TAG, "Camera #" + camIdx + "failed to open: " + e.getLocalizedMessage());
            }
            if (connected) break;
          }
        }
      } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
          int localCameraIndex = mCameraIndex;
          if (mCameraIndex == CAMERA_ID_BACK) {
            Log.i(TAG, "Trying to open back camera");
            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); ++camIdx) {
              Camera.getCameraInfo(camIdx, cameraInfo);
              if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
                localCameraIndex = camIdx;
                break;
              }
            }
          } else if (mCameraIndex == CAMERA_ID_FRONT) {
            Log.i(TAG, "Trying to open front camera");
            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); ++camIdx) {
              Camera.getCameraInfo(camIdx, cameraInfo);
              if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                localCameraIndex = camIdx;
                break;
              }
            }
          }
          if (localCameraIndex == CAMERA_ID_BACK) {
            Log.e(TAG, "Back camera not found!");
          } else if (localCameraIndex == CAMERA_ID_FRONT) {
            Log.e(TAG, "Front camera not found!");
          } else {
            Log.d(
                TAG,
                "Trying to open camera with new open(" + Integer.valueOf(localCameraIndex) + ")");
            try {
              mCamera = Camera.open(localCameraIndex);
            } catch (RuntimeException e) {
              Log.e(
                  TAG,
                  "Camera #" + localCameraIndex + "failed to open: " + e.getLocalizedMessage());
            }
          }
        }
      }

      if (mCamera == null) return false;

      /* Now set camera parameters */
      try {
        Camera.Parameters params = mCamera.getParameters();
        Log.d(TAG, "getSupportedPreviewSizes()");
        List<android.hardware.Camera.Size> sizes = params.getSupportedPreviewSizes();

        if (sizes != null) {
          /* Select the size that fits surface considering maximum size allowed */
          Size frameSize =
              calculateCameraFrameSize(sizes, new JavaCameraSizeAccessor(), width, height);

          params.setPreviewFormat(ImageFormat.NV21);
          Log.d(
              TAG,
              "Set preview size to "
                  + Integer.valueOf((int) frameSize.width)
                  + "x"
                  + Integer.valueOf((int) frameSize.height));
          params.setPreviewSize((int) frameSize.width, (int) frameSize.height);

          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH
              && !android.os.Build.MODEL.equals("GT-I9100")) params.setRecordingHint(true);

          List<String> FocusModes = params.getSupportedFocusModes();
          if (FocusModes != null
              && FocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
            params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
          }

          mCamera.setParameters(params);
          params = mCamera.getParameters();

          mFrameWidth = params.getPreviewSize().width;
          mFrameHeight = params.getPreviewSize().height;

          if ((getLayoutParams().width == LayoutParams.MATCH_PARENT)
              && (getLayoutParams().height == LayoutParams.MATCH_PARENT))
            mScale = Math.min(((float) height) / mFrameHeight, ((float) width) / mFrameWidth);
          else mScale = 0;

          if (mFpsMeter != null) {
            mFpsMeter.setResolution(mFrameWidth, mFrameHeight);
          }

          int size = mFrameWidth * mFrameHeight;
          size = size * ImageFormat.getBitsPerPixel(params.getPreviewFormat()) / 8;
          mBuffer = new byte[size];

          mCamera.addCallbackBuffer(mBuffer);
          mCamera.setPreviewCallbackWithBuffer(this);

          mFrameChain = new Mat[2];
          mFrameChain[0] = new Mat(mFrameHeight + (mFrameHeight / 2), mFrameWidth, CvType.CV_8UC1);
          mFrameChain[1] = new Mat(mFrameHeight + (mFrameHeight / 2), mFrameWidth, CvType.CV_8UC1);

          AllocateCache();

          mCameraFrame = new JavaCameraFrame[2];
          mCameraFrame[0] = new JavaCameraFrame(mFrameChain[0], mFrameWidth, mFrameHeight);
          mCameraFrame[1] = new JavaCameraFrame(mFrameChain[1], mFrameWidth, mFrameHeight);

          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mSurfaceTexture = new SurfaceTexture(MAGIC_TEXTURE_ID);
            mCamera.setPreviewTexture(mSurfaceTexture);
          } else mCamera.setPreviewDisplay(null);

          /* Finally we are ready to start the preview */
          Log.d(TAG, "startPreview");
          mCamera.startPreview();
        } else result = false;
      } catch (Exception e) {
        result = false;
        e.printStackTrace();
      }
    }

    return result;
  }