Android 默认情况下打开前摄像头

Android 默认情况下打开前摄像头,android,plugins,front-camera,Android,Plugins,Front Camera,我对android非常陌生,出于某种原因,我必须实现一个代码,默认情况下打开前摄像头而不是后摄像头。我的最小SDK是API 9,目标SDK是API 21。我有一个PicturePlugin.Java文件,代码是: public class PicturePlugin extends CordovaPlugin { private String callback="data"; private int IMAGE_TAKEN=1; private CallbackConte

我对android非常陌生,出于某种原因,我必须实现一个代码,默认情况下打开前摄像头而不是后摄像头。我的最小SDK是API 9,目标SDK是API 21。我有一个PicturePlugin.Java文件,代码是:

public class PicturePlugin extends CordovaPlugin
{
    private String callback="data";
    private int IMAGE_TAKEN=1;
    private CallbackContext callbackContext;    
    private String TAG="FilePlugin";
    private int imageWidth,imageHeight;
    private String imagePath;
    private File destImageFile;
    private String mode = "BACK";
    private static String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    CameraManager manager;
    private static final String TAG1 = null ;

    public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
    {
        this.callbackContext = callbackContext;
        this.cordova.getActivity().getApplicationContext().getPackageName();        
        try
        {
            JSONObject object=(JSONObject) args.get(0);
            imageWidth=object.getInt("targetWidth");
            imageHeight=object.getInt("targetHeight");
            if(object.has("mode")){
                if(object.getString("mode").equals("FRONT")){
                    mode = "FRONT";
                    openFrontFacingCamera();
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent.putExtra("android.intent.extras.CAMERA_FACING", android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);
                }
            }else{
                mode = "BACK";
            }
            Intent camera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            imagePath = getCapturedImageExternal();
            destImageFile = new File(imagePath);
            camera.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(destImageFile));
            this.cordova.setActivityResultCallback(PicturePlugin.this);
            cordova.getActivity().startActivityForResult(camera,IMAGE_TAKEN);
        }
        catch (Exception e)
        {
            Log.i(TAG, "Exception "+e.getMessage());
            callbackContext.error("failed");
        }
        return true;
    }


    private Camera openFrontFacingCamera()
    {
        int cameraCount = 0;
        Camera cam = null;
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        cameraCount = Camera.getNumberOfCameras();
        for ( int camId = 0; camId < cameraCount; camId++ ) {
            Camera.getCameraInfo( camId, cameraInfo );
            if ( cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT  ) {
                try {
                    cam = Camera.open( camId );
                } catch (RuntimeException e) {
                    Log.e(TAG1, "Camera failed to open: " + e.getLocalizedMessage());
                }
            }
        }

        return cam;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
        if (requestCode == IMAGE_TAKEN && resultCode == Activity.RESULT_OK) {
            File finalFile = null;
            File fileTobeDeleted = null;
            Bitmap photo = null;
            File sd = new File(Environment.getExternalStorageDirectory(),
                    Constants.GOBIZMO_IMAGE_DIR);
            String destinationImagePath = File.separator 
                    + Constants.TEMP_CAMERA_IMAGE + ".JPEG";
            File destination = new File(sd, destinationImagePath);
            sd.setWritable(true);

            try {
                String encoded;
                imagePath = destImageFile.getAbsolutePath();
                finalFile = new File(imagePath);
                fileTobeDeleted = new File(imagePath);
                int angle = getAngle(finalFile.getAbsolutePath());
                    if (finalFile.exists()) {
                        photo = BitmapFactory.decodeFile(finalFile
                                .getAbsolutePath());
                        Matrix matrix = new Matrix();
                        matrix.postRotate(angle);
                        Bitmap scaledBitmap = Bitmap.createScaledBitmap(photo, imageWidth, imageHeight, true);
                        photo = Bitmap.createBitmap(scaledBitmap, 0, 0, imageWidth, imageHeight, matrix, true);
                        // //////New orientation fix for all
                        // devices///////////////////////
                        try {
                            ByteArrayOutputStream stream = new ByteArrayOutputStream();
                                photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
                            byte[] byteArray = stream.toByteArray();
                            encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
                            Log.e("base 64 image", encoded);
                            JSONObject object = new JSONObject();
                            object.put(callback, encoded);
                            finalFile.delete();
                            fileTobeDeleted.delete();
                            //imagePath = destination.getPath();
                            if(new File(imagePath).exists()){
                                new File(imagePath).delete();
                            }
                            callbackContext.success(encoded);
                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.i(TAG, "onActivityResult " + e.getMessage());
                            finalFile.delete();
                            fileTobeDeleted.delete();

                            if(new File(imagePath).exists()){
                                new File(imagePath).delete();
                            }
                            callbackContext.error("failed");

                        } 
                    }
            } catch (Exception exp) {
                exp.printStackTrace();
                Log.i(TAG, "onActivityResult " + exp.getMessage());
                try {
                    finalFile.delete();
                    fileTobeDeleted.delete();
                    imagePath = destination.getPath();
                    if(new File(imagePath).exists()){
                        new File(imagePath).delete();
                    }
                    callbackContext.error("failed");
                }catch(Exception innerexception){
                    innerexception.printStackTrace();
                }
            }
        }
    }

    public Uri getImageUri(Context inContext, Bitmap inImage)
    {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
        return Uri.parse(path);
    }

    public String getRealPathFromURI(Uri uri)
    {
        Cursor cursor = cordova.getActivity().getContentResolver().query(uri, null, null, null, null); 
        cursor.moveToFirst(); 
        int idx = cursor.getColumnIndex(Images.ImageColumns.DATA);
        return cursor.getString(idx); 
    }


    public static String getCapturedImageExternal() {

        // External sdcard location
        File mediaStorageDir = new File(
                android.os.Environment.getExternalStorageDirectory(),
                "Gobizmo image");
        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()){
            mediaStorageDir.mkdirs();
        }
        if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()) {
            Log.d(Constants.GOBIZMO_IMAGE_DIR, "Oops! Failed create "
                    + Constants.GOBIZMO_IMAGE_DIR + " directory");
            return null;
        }
        // Create a timestamp

        return mediaStorageDir.getPath() + File.separator + Constants.TEMP_CAMERA_IMAGE
                + ".JPEG";
    }

    public static String getRealPathFromURI(Context context, Uri contentUri) {
        String filepath = "";
        String uriPath = contentUri.toString();
        // Handle local file and remove url encoding
        if (uriPath.startsWith("file://")) {
            filepath = uriPath.replace("file://", "");
            try {
                return URLDecoder.decode(filepath, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        try {
            String[] projection = { MediaStore.Images.Media.DATA };
            Cursor cursor = context.getContentResolver().query(contentUri,
                    projection, null, null, null);
            if (cursor != null && cursor.getCount() != 0) {
                int column_index = cursor
                        .getColumnIndex(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                filepath = cursor.getString(column_index);
            }
        } catch (Exception e) {
            Log.e("Path Error", e.toString());
        }
        return filepath;
    }

    private int getAngle(String path)
    {
        int angle=0;
        try
        {       
            ExifInterface ei = new ExifInterface(path);
            int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            Log.i(TAG, "getAngle "+orientation);

            switch(orientation)
            {
                case ExifInterface.ORIENTATION_ROTATE_90:
                                                            angle=90;
                                                            break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                                                            angle=180;
                                                            break;
                case ExifInterface.ORIENTATION_ROTATE_270 :
                                                            angle=270;
                default:
                                                            angle=0;
            }
        }
        catch(Exception ex)
        {
            Log.i("getAngle", "getAngle :: "+ex.getMessage());
        }
        return angle;
    }

}
公共类PicturePlugin扩展了CordovaPlugin
{
私有字符串callback=“data”;
私人int图像_拍摄=1;
私有CallbackContext CallbackContext;
私有字符串TAG=“FilePlugin”;
私有int-imageWidth、imageHeight;
私有字符串路径;
私有文件;
私有字符串模式=“返回”;
私有静态字符串时间戳=新的SimpleDataFormat(“yyyyMMdd_HHmmss”,
Locale.getDefault()).format(新日期());
摄像管理员;
私有静态最终字符串TAG1=null;
公共布尔执行(字符串操作、JSONArray参数、CallbackContext CallbackContext)
{
this.callbackContext=callbackContext;
this.cordova.getActivity().getApplicationContext().getPackageName();
尝试
{
JSONObject对象=(JSONObject)args.get(0);
imageWidth=object.getInt(“targetWidth”);
imageHeight=object.getInt(“targetHeight”);
if(object.has(“mode”)){
if(object.getString(“mode”).equals(“FRONT”)){
mode=“FRONT”;
打开正面摄像头();
意向意向=新意向(MediaStore.ACTION\u IMAGE\u CAPTURE);
intent.putExtra(“android.intent.extras.CAMERA_-FACING”,android.hardware.CAMERA.CameraInfo.CAMERA_-FACING_-FRONT”);
}
}否则{
mode=“后退”;
}
意向照相机=新意向(MediaStore.ACTION\u IMAGE\u CAPTURE);
imagePath=getCapturedImageExternal();
DestinmageFile=新文件(imagePath);
camera.putExtra(MediaStore.EXTRA_输出,
fromFile(destImageFile));
this.cordova.setActivityResultCallback(PicturePlugin.this);
cordova.getActivity().startActivityForResult(照相机,拍摄的图像);
}
捕获(例外e)
{
Log.i(标记“Exception”+e.getMessage());
callbackContext.error(“失败”);
}
返回true;
}
私人摄像机openFrontFacingCamera()
{
int cameraCount=0;
摄像机摄像机=null;
Camera.CameraInfo CameraInfo=新的Camera.CameraInfo();
cameraCount=Camera.getNumberOfCameras();
对于(int-camId=0;camIdobject.getString("mode").equals("FRONT")
 Activity activity = getActivity();
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        for (String cameraId : manager.getCameraIdList()) {
            CameraCharacteristics characteristics
                    = manager.getCameraCharacteristics(cameraId);

            // Choose front or back lens
            Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);

            if (facing != null && facing == CameraCharacteristics.LENS_FACING_BACK) {
                continue;
            }
private Camera openFrontFacingCameraGingerbread() {
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx<cameraCount; camIdx++) {
    Camera.getCameraInfo(camIdx, cameraInfo);
    if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
        try {
            cam = Camera.open(camIdx);
        } catch (RuntimeException e) {
            Log.e("Your_TAG", "Camera failed to open: " + e.getLocalizedMessage());
        }
    }
}
return cam;
}
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONObject;
import org.maxmobility.util.Constants;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;

import android.hardware.camera2.CameraManager;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Base64;
import android.util.Log;
import android.view.SurfaceHolder;


public class PicturePlugin extends CordovaPlugin
{
    private String callback="data";
    private int IMAGE_TAKEN=1;
    private CallbackContext callbackContext;    
    private String TAG="FilePlugin";
    private int imageWidth,imageHeight;
    private String imagePath;
    private File destImageFile;
    private String mode = "BACK";
    private static String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    static Camera camera = null;
    private static final String TAG1 = null ;

    public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
    {
        this.callbackContext = callbackContext;
        this.cordova.getActivity().getApplicationContext().getPackageName();        
        try
        {
            JSONObject object=(JSONObject) args.get(0);
            imageWidth=object.getInt("targetWidth");
            imageHeight=object.getInt("targetHeight");
            //checking whether json object has "mode" or not
            if(object.has("mode"))
            {
                //if json object has "mode" and that is "FRONT"
                if(object.getString("mode").equals("FRONT"))
                {
                    mode = "FRONT";
                    Intent camera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    camera.putExtra("android.intent.extras.CAMERA_FACING", 1); // used this line of code to start the intent of camera
                                                                                //The ID is 1 that opens FRONT CAMERA of a device
                    imagePath = getCapturedImageExternal();
                    destImageFile = new File(imagePath);
                    camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destImageFile));

                    this.cordova.setActivityResultCallback(PicturePlugin.this);
                    cordova.getActivity().startActivityForResult(camera,IMAGE_TAKEN);


                }
                else
                {   
                    // if json object has "mode" and that is "BACK"
                    mode = "BACK";
                    Intent camera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    camera.putExtra("android.intent.extras.CAMERA_FACING", 0);  //ID is 0 that opens REAR CAMERA of a device
                    imagePath = getCapturedImageExternal();
                    destImageFile = new File(imagePath);
                    camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destImageFile));

                    this.cordova.setActivityResultCallback(PicturePlugin.this);
                    cordova.getActivity().startActivityForResult(camera,IMAGE_TAKEN);
                }


            }
            else
            {

                //if no "mode" is found in json object then by default rear camera is opening
                Intent camera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                camera.putExtra("android.intent.extras.CAMERA_FACING", 0);
                imagePath = getCapturedImageExternal();
                destImageFile = new File(imagePath);
                camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destImageFile));

                this.cordova.setActivityResultCallback(PicturePlugin.this);
                cordova.getActivity().startActivityForResult(camera,IMAGE_TAKEN);
            }
        }       

        catch (Exception e)
        {
            Log.i(TAG, "Exception "+e.getMessage());
            callbackContext.error("failed");

        }
        return true;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
        if (requestCode == IMAGE_TAKEN && resultCode == Activity.RESULT_OK) {
            File finalFile = null;
            File fileTobeDeleted = null;
            Bitmap photo = null;
            File sd = new File(Environment.getExternalStorageDirectory(),
                    Constants.GOBIZMO_IMAGE_DIR);
            String destinationImagePath = File.separator 
                    + Constants.TEMP_CAMERA_IMAGE + ".JPEG";
            File destination = new File(sd, destinationImagePath);
            sd.setWritable(true);

            try {


                String encoded;
                imagePath = destImageFile.getAbsolutePath();


                finalFile = new File(imagePath);
                fileTobeDeleted = new File(imagePath);
                int angle = getAngle(finalFile.getAbsolutePath());








                    if (finalFile.exists()) {
                        photo = BitmapFactory.decodeFile(finalFile
                                .getAbsolutePath());
                        Matrix matrix = new Matrix();
                        matrix.postRotate(angle);
                        Bitmap scaledBitmap = Bitmap.createScaledBitmap(photo, imageWidth, imageHeight, true);
                        photo = Bitmap.createBitmap(scaledBitmap, 0, 0, imageWidth, imageHeight, matrix, true);
                        // //////New orientation fix for all
                        // devices///////////////////////

                        try {


                            ByteArrayOutputStream stream = new ByteArrayOutputStream();
                                photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
                            byte[] byteArray = stream.toByteArray();
                            encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
                            Log.e("base 64 image", encoded);
                            JSONObject object = new JSONObject();
                            object.put(callback, encoded);
                            finalFile.delete();
                            fileTobeDeleted.delete();
                            //imagePath = destination.getPath();
                            if(new File(imagePath).exists()){
                                new File(imagePath).delete();
                            }
                            callbackContext.success(encoded);
                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.i(TAG, "onActivityResult " + e.getMessage());
                            finalFile.delete();
                            fileTobeDeleted.delete();

                            if(new File(imagePath).exists()){
                                new File(imagePath).delete();
                            }
                            callbackContext.error("failed");

                        } 
                    }




            } catch (Exception exp) {
                exp.printStackTrace();
                Log.i(TAG, "onActivityResult " + exp.getMessage());
                try {
                    finalFile.delete();
                    fileTobeDeleted.delete();
                    imagePath = destination.getPath();
                    if(new File(imagePath).exists()){
                        new File(imagePath).delete();
                    }
                    callbackContext.error("failed");
                }catch(Exception innerexception){
                    innerexception.printStackTrace();
                }
            }
        }
    }

    public Uri getImageUri(Context inContext, Bitmap inImage)
    {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
        return Uri.parse(path);
    }

    public String getRealPathFromURI(Uri uri)
    {
        Cursor cursor = cordova.getActivity().getContentResolver().query(uri, null, null, null, null); 
        cursor.moveToFirst(); 
        int idx = cursor.getColumnIndex(Images.ImageColumns.DATA);
        return cursor.getString(idx); 
    }


    public static String getCapturedImageExternal() {

        // External sdcard location
        File mediaStorageDir = new File(
                android.os.Environment.getExternalStorageDirectory(),
                "Gobizmo image");
        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()){
            mediaStorageDir.mkdirs();
        }
        if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()) {
            Log.d(Constants.GOBIZMO_IMAGE_DIR, "Oops! Failed create "
                    + Constants.GOBIZMO_IMAGE_DIR + " directory");
            return null;
        }
        // Create a timestamp


        return mediaStorageDir.getPath() + File.separator + Constants.TEMP_CAMERA_IMAGE
                + ".JPEG";
    }


    public static String getRealPathFromURI(Context context, Uri contentUri) {
        String filepath = "";
        String uriPath = contentUri.toString();
        // Handle local file and remove url encoding
        if (uriPath.startsWith("file://")) {
            filepath = uriPath.replace("file://", "");
            try {
                return URLDecoder.decode(filepath, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        try {
            String[] projection = { MediaStore.Images.Media.DATA };
            Cursor cursor = context.getContentResolver().query(contentUri,
                    projection, null, null, null);
            if (cursor != null && cursor.getCount() != 0) {
                int column_index = cursor
                        .getColumnIndex(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                filepath = cursor.getString(column_index);
            }
        } catch (Exception e) {
            Log.e("Path Error", e.toString());
        }
        return filepath;
    }

    private int getAngle(String path)
    {
        int angle=0;
        try
        {       
            ExifInterface ei = new ExifInterface(path);
            int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            Log.i(TAG, "getAngle "+orientation);

            switch(orientation)
            {
                case ExifInterface.ORIENTATION_ROTATE_90:
                                                            angle=90;
                                                            break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                                                            angle=180;
                                                            break;
                case ExifInterface.ORIENTATION_ROTATE_270 :
                                                            angle=270;
                default:
                                                            angle=0;
            }
        }
        catch(Exception ex)
        {
            Log.i("getAngle", "getAngle :: "+ex.getMessage());
        }
        return angle;
    }

}
<uses-feature android:name="android.hardware.camera.front"   /> <!-- used this feature to open the front camera  -->