From ff3a882198b17860d0ab1602c489f68ccb957f95 Mon Sep 17 00:00:00 2001
From: xuxiuxi <xuxiuxi@454eff88-639b-444f-9e54-f578c98de674>
Date: 星期三, 19 七月 2017 17:26:28 +0800
Subject: [PATCH] 

---
 VisitFace/DemoForBsk/app/src/main/java/cn/com/basic/face/base/MainActivity.java |  344 ++++++++++++++++++++++++++++++++++++++++++---------------
 1 files changed, 252 insertions(+), 92 deletions(-)

diff --git a/VisitFace/DemoForBsk/app/src/main/java/cn/com/basic/face/base/MainActivity.java b/VisitFace/DemoForBsk/app/src/main/java/cn/com/basic/face/base/MainActivity.java
index 3427a76..40d4ed5 100644
--- a/VisitFace/DemoForBsk/app/src/main/java/cn/com/basic/face/base/MainActivity.java
+++ b/VisitFace/DemoForBsk/app/src/main/java/cn/com/basic/face/base/MainActivity.java
@@ -1,31 +1,37 @@
 package cn.com.basic.face.base;
 
+import android.Manifest;
 import android.app.AlertDialog;
 import android.content.Context;
 import android.content.DialogInterface;
-import android.content.Intent;
 import android.content.pm.ActivityInfo;
+import android.content.pm.PackageManager;
 import android.content.res.Configuration;
 import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
 import android.graphics.Canvas;
 import android.graphics.Color;
+import android.graphics.ImageFormat;
 import android.graphics.Paint;
-import android.graphics.drawable.ColorDrawable;
+import android.graphics.PorterDuff;
+import android.graphics.SurfaceTexture;
 import android.hardware.Camera;
 import android.os.Handler;
 import android.support.design.widget.TabLayout;
+import android.support.v4.app.ActivityCompat;
 import android.support.v4.app.Fragment;
 import android.support.v4.app.FragmentManager;
 import android.support.v4.app.FragmentPagerAdapter;
+import android.support.v4.content.ContextCompat;
 import android.support.v4.view.ViewPager;
 import android.os.Bundle;
 import android.view.LayoutInflater;
 import android.view.MotionEvent;
 import android.view.SurfaceHolder;
 import android.view.SurfaceView;
+import android.view.TextureView;
 import android.view.View;
 import android.view.ViewGroup;
-import android.view.Window;
 import android.view.WindowManager;
 import android.widget.EditText;
 import android.widget.ImageView;
@@ -33,13 +39,16 @@
 import android.widget.TextView;
 import android.widget.Toast;
 
+import com.awsle.aibatis.client.SqlMapClientBuilder;
 import com.bsk.zhangbo.demoforbsk.R;
 import com.luxand.FSDK;
 
 import cn.com.basic.face.discern.common.CommonVariables;
 import cn.com.basic.face.discern.query.item.SurveillanceQueryItem;
+import cn.com.basic.face.fragment.AttenderRegisterFragment;
 import cn.com.basic.face.fragment.SurveillanceFragment;
 import cn.com.basic.face.service.SurveillanceMng;
+import cn.com.basic.face.service.sqlite.TestDao;
 import cn.com.basic.face.util.FileUtil;
 import cn.com.basic.face.util.NativeImg;
 import cn.com.basic.face.util.TabNameUtil;
@@ -47,13 +56,14 @@
 import cn.com.basic.face.fragment.CheckInFragment;
 import cn.com.basic.face.fragment.DeviceFragment;
 import cn.com.basic.face.fragment.PhoneCallFragment;
-import cn.com.basic.face.fragment.RegisterFragment;
+import cn.com.basic.face.fragment.VisitorRegisterFragment;
 import cn.com.basic.face.fragment.VisitFragment;
 
 import java.io.File;
+import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
+import java.io.IOException;
 import java.io.InputStream;
-import java.nio.ByteBuffer;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
@@ -65,7 +75,7 @@
     private static MainActivity instance;
 
     private static TabLayout mTabLayout;
-    private static ViewPager mViewPager;
+    public static ViewPager mViewPager;
 
     public static void selectPage(int pageNum) {
         mTabLayout.getTabAt(pageNum).select();
@@ -84,13 +94,17 @@
         instance = this;
     }
 
+    public MyFragmentPagerAdapter myFragmentPagerAdapter;
+
     @Override
     public void initData() {
         List<String> tabNamesList = Arrays.asList(TabNameUtil.tabNames);
         int[] tabIcons = TabNameUtil.tabIcons;
-        MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(),MainActivity.this);
+        myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(),MainActivity.this);
         myFragmentPagerAdapter.addFragment(SurveillanceFragment.getInstance(), tabNamesList.get(0),tabIcons[0]);
-        myFragmentPagerAdapter.addFragment(RegisterFragment.getInstance(), tabNamesList.get(1),tabIcons[1]);
+        myFragmentPagerAdapter.addFragment(VisitorRegisterFragment.getInstance(), tabNamesList.get(1),tabIcons[1]);
+//        myFragmentPagerAdapter.addFragment(AttenderRegisterFragment.getInstance(), tabNamesList.get(1),tabIcons[1]);
+//        myFragmentPagerAdapter.addFragment(RegisterFragment.getInstance(), tabNamesList.get(1),tabIcons[1]);
         myFragmentPagerAdapter.addFragment(CheckInFragment.getInstance(), tabNamesList.get(2),tabIcons[2]);
         myFragmentPagerAdapter.addFragment(PhoneCallFragment.getInstance(), tabNamesList.get(3),tabIcons[3]);
         myFragmentPagerAdapter.addFragment(VisitFragment.getInstance(), tabNamesList.get(4),tabIcons[4]);
@@ -108,9 +122,12 @@
                 tab.getCustomView().setSelected(true);
             }
         }
-        myThread = new MyThread();
-        myThread.start();
-
+        if (CommonVariables.ID_CARD) {
+            myThread = new MyThread();
+            myThread.start();
+        }
+        initDb();
+        initSqlMap();
     }
 
     public static MainActivity getInstance() {
@@ -132,6 +149,12 @@
             mFragments.add(fragment);
             mFragmentTitles.add(title);
             mFragmentIcons.add(drawable);
+        }
+
+        public void setFragment(int index, Fragment fragment) {
+            mFragments.remove(index);
+            mFragments.add(index, fragment);
+            notifyDataSetChanged();
         }
 
         @Override
@@ -249,14 +272,65 @@
         }
         return true;
     }
+/////////////////////////////
 
+    /**
+     * 鍒濆鍖杝qlMap
+     */
+    private void initSqlMap() {
+        Config.sqlMap = SqlMapClientBuilder.buildSqlMapClient(this.getClass().getResourceAsStream("/assets/config/SqlMapConfig.xml")).init(this);
+    }
+    /**
+     * 鍒濆鍖栨暟鎹�
+     */
+    private void initDb() {
+        InputStream dbIn = getClass().getResourceAsStream(Config.DB);
+        FileOutputStream out = null;
+        File z = null;
+        try {
+            byte[] bytes = new byte[1024];
+            z = new File(Config.APPDBPATH);
+            if(!z.exists()){
+                z.mkdirs();
+            }
+            //鍒ゆ柇鏁版嵁搴撴槸鍚﹀瓨鍦�
+            z = new File(Config.APPDB);
+            if (!z.exists()) {
+                out = new FileOutputStream(z);
+                int len = 0;
+                while((len = dbIn.read(bytes))!= -1){
+                    out.write(bytes,0,len);
+                }
+            }
+        } catch (FileNotFoundException e) {
+            e.printStackTrace();
+        } catch (IOException e) {
+            e.printStackTrace();
+        } finally {
+            try {
+                if (out != null)
+                    out.close();
+                if (dbIn != null)
+                    dbIn.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        try {
+            //瀵规暟鎹簱鏂囦欢鏉冮檺
+            Runtime.getRuntime().exec("chmod 7755 " + z.toString());
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        //Log.d(Config.APPTAG, "鍒濆鍖栨暟鎹畬鎴愶紒");
+    }
 
     ////////////////////////////////////////////////////////
     private boolean mIsFailed = false;
     public Preview mPreview;
     public ProcessImageAndDrawResults mDraw;
     private final String database = "Memory50.dat";
-    private final String help_text = "Luxand Face Recognition\n\nJust tap any detected face and name it. The app will recognize this face further. For best results, hold the device at arm's length. You may slowly rotate the head for the app to memorize you at multiple views. The app can memorize several persons. If a face is not recognized, tap and name it again.\n\nThe SDK is available for mobile developers: www.luxand.com/facesdk";
+    private final String help_text = "help";
 
     public static float sDensity = 1.0f;
 
@@ -266,21 +340,14 @@
         if (CommonVariables.FACE_SERVER) {
             sDensity = getResources().getDisplayMetrics().scaledDensity;
 
-            int res = FSDK.ActivateLibrary("bSB3NdbTnv/0eW/uhypSe6hDMtjZ76Sisw5NwcN+0sfahxOtoUW22el54e/M6cSG5/xsdVIorPgugbTIfoIIn7ltyw1QMSleNebVx/Xe8aRA8bP+aVDybjoWdW/0rDP9Pv7yqBzNXyuwjgsVhPB53VGP8oTirTSUP7PTzSwOEe0=");
+            int res = 0;
             if (res != FSDK.FSDKE_OK) {
                 mIsFailed = true;
-                showErrorAndClose("FaceSDK activation failed", res);
+                showErrorAndClose("failed", res);
             } else {
                 FSDK.Initialize();
-
-                // Hide the window title (it is done in manifest too)
                 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
-//z                requestWindowFeature(Window.FEATURE_NO_TITLE);
-
-                // Lock orientation
                 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
-
-                // Camera layer and drawing layer
                 mDraw = new ProcessImageAndDrawResults(this);
                 mPreview = new Preview(this, mDraw);
                 mDraw.mTracker = new FSDK.HTracker();
@@ -291,22 +358,17 @@
                         showErrorAndClose("Error creating tracker", res);
                     }
                 }
-
                 resetTrackerParameters();
 
-                //this.getWindow().setBackgroundDrawable(new ColorDrawable()); //black background
-
                 //setContentView(mPreview); //creates MainActivity contents
-                //addContentView(mDraw, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
-
+                //addContentView(mDraw, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
 
                 // Menu
 //                LayoutInflater inflater = (LayoutInflater)this.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
 //                View buttons = inflater.inflate(R.layout.bottom_menu, null );
 //                buttons.findViewById(R.id.helpButton).setOnClickListener(this);
 //                buttons.findViewById(R.id.clearButton).setOnClickListener(this);
-//                addContentView(buttons, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
-
+//                addContentView(buttons, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
             }
         }
     }
@@ -331,7 +393,7 @@
                             @Override public void onClick(DialogInterface dialogInterface, int j) {
                             }
                         })
-                        .setCancelable(false) // cancel with button only
+                        .setCancelable(false)
                         .show();
             }
         }
@@ -377,7 +439,7 @@
                     public void onClick(DialogInterface dialogInterface, int i) {
                     }
                 })
-                .setCancelable(false) // cancel with button only
+                .setCancelable(false)
                 .show();
     }
 
@@ -392,7 +454,6 @@
     private void pauseProcessingFrames() {
         mDraw.mStopping = 1;
 
-        // It is essential to limit wait time, because mStopped will not be set to 0, if no frames are feeded to mDraw
         for (int i=0; i<100; ++i) {
             if (mDraw.mStopped != 0) break;
             try { Thread.sleep(10); }
@@ -404,6 +465,7 @@
         mDraw.mStopped = 0;
         mDraw.mStopping = 0;
     }
+
 }
 
 
@@ -412,7 +474,6 @@
     public int x1, y1, x2, y2;
 }
 
-// Draw graphics on top of the video
 class ProcessImageAndDrawResults extends View {
     public FSDK.HTracker mTracker;
 
@@ -485,15 +546,13 @@
         mPaintBlueTransparent.setColor(Color.BLUE);
         mPaintBlueTransparent.setTextSize(25);
 
-        //mBitmap = null;
         mYUVData = null;
         mRGBData = null;
 
         first_frame_saved = false;
     }
 
-    @Override
-    protected void onDraw(Canvas canvas) {
+    public void onDraw(Canvas canvas) {
         if (mStopping == 1) {
             mStopped = 1;
             super.onDraw(canvas);
@@ -502,16 +561,13 @@
 
         if (mYUVData == null || mTouchedIndex != -1) {
             super.onDraw(canvas);
-            return; //nothing to process or name is being entered now
+            return;
         }
 
         int canvasWidth = canvas.getWidth();
-        //int canvasHeight = canvas.getHeight();
 
-        // Convert from YUV to RGB
         decodeYUV420SP(mRGBData, mYUVData, mImageWidth, mImageHeight);
 
-        // Load image to FaceSDK
         FSDK.HImage Image = new FSDK.HImage();
         FSDK.FSDK_IMAGEMODE imagemode = new FSDK.FSDK_IMAGEMODE();
         imagemode.mode = FSDK.FSDK_IMAGEMODE.FSDK_IMAGE_COLOR_24BIT;
@@ -520,34 +576,36 @@
         FSDK.HImage RotatedImage = new FSDK.HImage();
         FSDK.CreateEmptyImage(RotatedImage);
 
-//        FSDK.SaveImageToFile(Image, MainActivity.getInstance().getFilesDir().getAbsolutePath()+System.currentTimeMillis()+".jpg");
-
-        //it is necessary to work with local variables (onDraw called not the time when mImageWidth,... being reassigned, so swapping mImageWidth and mImageHeight may be not safe)
         int ImageWidth = mImageWidth;
-        //int ImageHeight = mImageHeight;
         if (rotated) {
             ImageWidth = mImageHeight;
-            //ImageHeight = mImageWidth;
             FSDK.RotateImage90(Image, -1, RotatedImage);
         } else {
             FSDK.CopyImage(Image, RotatedImage);
         }
-        FSDK.FreeImage(Image);
 
-        // Save first frame to gallery to debug (e.g. rotation angle)
-		/*
-		if (!first_frame_saved) {
-			first_frame_saved = true;
-			String galleryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath();
-			FSDK.SaveImageToFile(RotatedImage, galleryPath + "/first_frame.jpg"); //frame is rotated!
-		}
-		*/
+//        FSDK.TFacePosition fp11 = new FSDK.TFacePosition();
+//        FSDK.DetectFace(RotatedImage, fp11);
+        FSDK.FSDK_FaceTemplate face = new FSDK.FSDK_FaceTemplate();
+        int result = FSDK.GetFaceTemplate(RotatedImage, face);
+        if (result == FSDK.FSDKE_OK) {
+
+        }
+
+        String surveillancePhotoName11 = "/storage/sdcard1/"+System.currentTimeMillis()+".jpg";
+        FSDK.SaveImageToFile(Image, surveillancePhotoName11);
+
+
+        FSDK.FreeImage(Image);
 
         long IDs[] = new long[MAX_FACES];
         long face_count[] = new long[1];
 
+
+
         FSDK.FeedFrame(mTracker, 0, RotatedImage, face_count, IDs);
-//        FSDK.FreeImage(RotatedImage);
+
+        System.out.println("face_count="+face_count[0]+", mImageWidth="+mImageWidth+", mImageHeight="+mImageHeight);
 
         faceLock.lock();
 
@@ -602,13 +660,20 @@
                 nativeImg.size = nativeImg.image.length;
                 SurveillanceQueryItem surveillanceQueryItem = new SurveillanceQueryItem();
                 surveillanceQueryItem.setNativeImg(nativeImg);
-                //surveillanceQueryItem.setBitmap(bitmap);
+                nativeImg.st_track_id = 1;
+                surveillanceQueryItem.setStTrackId(nativeImg.st_track_id);
+                BitmapFactory.Options options = new BitmapFactory.Options();
+                options.inMutable = true;
+                Bitmap bmp = BitmapFactory.decodeByteArray(nativeImg.image, 0, nativeImg.image.length, options);
+                Canvas canvas1 = new Canvas(bmp);
+
+                surveillanceQueryItem.setBitmap(bmp);
                 surveillanceQueryItem.setWidth("100");
                 surveillanceQueryItem.setHeight("100");
                 bitmapList.add(surveillanceQueryItem);
 
 
-                SurveillanceMng.getInstance().addBitmap(bitmapList, nativeImg.image, 0, CommonVariables.Camera.IN+"");
+                SurveillanceMng.getInstance().addBitmap(bitmapList, nativeImg.image, 0, CommonVariables.Camera.IN+"", nativeImg.image);
             }
 
         }
@@ -617,7 +682,6 @@
 
         int shift = (int)(22 * MainActivity.sDensity);
 
-        // Mark and name faces
         for (int i=0; i<face_count[0]; ++i) {
             canvas.drawRect(mFacePositions[i].x1, mFacePositions[i].y1, mFacePositions[i].x2, mFacePositions[i].y2, mPaintBlueTransparent);
 
@@ -636,7 +700,7 @@
         }
 
         super.onDraw(canvas);
-    } // end onDraw method
+    }
 
 
     @Override
@@ -665,7 +729,6 @@
 
                         mTouchedIndex = i;
 
-                        // requesting name on tapping the face
                         final EditText input = new EditText(mContext);
                         AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                         builder.setMessage("Enter person's name" )
@@ -683,7 +746,7 @@
                                         mTouchedIndex = -1;
                                     }
                                 })
-                                .setCancelable(false) // cancel with button only
+                                .setCancelable(false)
                                 .show();
 
                         break;
@@ -720,12 +783,121 @@
             }
         }
     }
-} // end of ProcessImageAndDrawResults class
+
+    public void startFaceDetection() {
+        if (mStopping == 1) {
+            mStopped = 1;
+            return;
+        }
+
+        if (mYUVData == null || mTouchedIndex != -1) {
+            return;
+        }
+
+
+        decodeYUV420SP(mRGBData, mYUVData, mImageWidth, mImageHeight);
+
+        FSDK.HImage Image = new FSDK.HImage();
+        FSDK.FSDK_IMAGEMODE imagemode = new FSDK.FSDK_IMAGEMODE();
+        imagemode.mode = FSDK.FSDK_IMAGEMODE.FSDK_IMAGE_COLOR_24BIT;
+        FSDK.LoadImageFromBuffer(Image, mRGBData, mImageWidth, mImageHeight, mImageWidth*3, imagemode);
+        FSDK.MirrorImage(Image, false);
+        FSDK.HImage RotatedImage = new FSDK.HImage();
+        FSDK.CreateEmptyImage(RotatedImage);
+
+        int ImageWidth = mImageWidth;
+        if (rotated) {
+            ImageWidth = mImageHeight;
+            FSDK.RotateImage90(Image, -1, RotatedImage);
+        } else {
+            FSDK.CopyImage(Image, RotatedImage);
+        }
+
+        //String surveillancePhotoName11 = "/storage/sdcard1/"+System.currentTimeMillis()+".jpg";
+        //FSDK.SaveImageToFile(Image, surveillancePhotoName11);
+
+
+        FSDK.FreeImage(Image);
+
+        long IDs[] = new long[MAX_FACES];
+        long face_count[] = new long[1];
+
+
+
+        FSDK.FeedFrame(mTracker, 0, RotatedImage, face_count, IDs);
+
+        System.out.println("face_count="+face_count[0]+", mImageWidth="+mImageWidth+", mImageHeight="+mImageHeight);
+
+        faceLock.lock();
+
+        for (int i=0; i<MAX_FACES; ++i) {
+            mFacePositions[i] = new FaceRectangle();
+            mFacePositions[i].x1 = 0;
+            mFacePositions[i].y1 = 0;
+            mFacePositions[i].x2 = 0;
+            mFacePositions[i].y2 = 0;
+            mIDs[i] = IDs[i];
+        }
+
+
+        for (int i = 0; i < (int)face_count[0]; ++i) {
+            FSDK.FSDK_Features Eyes = new FSDK.FSDK_Features();
+            FSDK.GetTrackerEyes(mTracker, 0, mIDs[i], Eyes);
+
+            GetFaceFrame(Eyes, mFacePositions[i]);
+        }
+        if ((int)face_count[0] > 0) {
+
+            FSDK.HImage img2 = new FSDK.HImage();
+            FSDK.CreateEmptyImage(img2);
+            FSDK.TFacePosition fp = new FSDK.TFacePosition();
+            FSDK.DetectFace(RotatedImage, fp);
+
+            int x1 = (int)(fp.xc - 1.2*fp.w/2);
+            int y1 = (int)(fp.yc - 1.4*fp.w/2);
+            int x2 = (int)(fp.xc + 1.2*fp.w/2);
+            int y2 = (int)(fp.yc + 1.4*fp.w/2);
+
+            FSDK.CopyRect(RotatedImage, x1, y1, x2, y2, img2);
+
+
+            System.out.println("face_count="+face_count[0]);
+            String surveillancePhotoName = MainActivity.getInstance().getFilesDir().getAbsolutePath()+System.currentTimeMillis()+".jpg";
+            FSDK.SaveImageToFile(img2, surveillancePhotoName);
+
+            List bitmapList = new ArrayList();
+            for (int i = 0; i < 1; i++) {
+                NativeImg nativeImg = new NativeImg();
+                nativeImg.image = FileUtil.readFile(new File(surveillancePhotoName));
+                nativeImg.size = nativeImg.image.length;
+                SurveillanceQueryItem surveillanceQueryItem = new SurveillanceQueryItem();
+                surveillanceQueryItem.setNativeImg(nativeImg);
+                nativeImg.st_track_id = 1;
+                surveillanceQueryItem.setStTrackId(nativeImg.st_track_id);
+                BitmapFactory.Options options = new BitmapFactory.Options();
+                options.inMutable = true;
+                Bitmap bmp = BitmapFactory.decodeByteArray(nativeImg.image, 0, nativeImg.image.length, options);
+                Canvas canvas1 = new Canvas(bmp);
+
+                surveillanceQueryItem.setBitmap(bmp);
+                surveillanceQueryItem.setWidth("100");
+                surveillanceQueryItem.setHeight("100");
+                bitmapList.add(surveillanceQueryItem);
+
+
+                SurveillanceMng.getInstance().addBitmap(bitmapList, nativeImg.image, 0, CommonVariables.Camera.IN+"", nativeImg.image);
+            }
 
 
 
 
-// Show video from camera and pass frames to ProcessImageAndDraw class
+        }
+        FSDK.FreeImage(RotatedImage);
+        faceLock.unlock();
+
+    }
+}
+
 class Preview extends SurfaceView implements SurfaceHolder.Callback {
     Context mContext;
     SurfaceHolder mHolder;
@@ -738,46 +910,48 @@
         mContext = context;
         mDraw = draw;
 
-        //Install a SurfaceHolder.Callback so we get notified when the underlying surface is created and destroyed.
         mHolder = getHolder();
         mHolder.addCallback(this);
         mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
+
+        //new MyThread1().start();
     }
 
-    //SurfaceView callback
+    int count = 0;
     public void surfaceCreated(SurfaceHolder holder) {
         mFinished = false;
 
-        // Find the ID of the camera
         int cameraId = 0;
         boolean frontCameraFound = false;
         Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
         for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
             Camera.getCameraInfo(i, cameraInfo);
-            //if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK)
             if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                 cameraId = i;
                 frontCameraFound = true;
             }
         }
-
+        //If authorisation not granted for camera
+        if (ContextCompat.checkSelfPermission(MainActivity.getInstance(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
+            //ask for authorisation
+            ActivityCompat.requestPermissions(MainActivity.getInstance(), new String[]{Manifest.permission.CAMERA}, 50);
         if (frontCameraFound) {
             mCamera = Camera.open(cameraId);
         } else {
             mCamera = Camera.open();
         }
-
         try {
             mCamera.setPreviewDisplay(holder);
 
-            // Preview callback used whenever new viewfinder frame is available
-            mCamera.setPreviewCallback(new Camera.PreviewCallback() {
-                public void onPreviewFrame(byte[] data, Camera camera) {
+            mCamera.addCallbackBuffer(new byte[((640 * 480) * ImageFormat.getBitsPerPixel(ImageFormat.NV21)) / 8]);
+
+            //mCamera.setPreviewCallback
+            mCamera.setPreviewCallbackWithBuffer(new Camera.PreviewCallback() {
+                public void onPreviewFrame(final byte[] data, final Camera camera) {
+                    mCamera.addCallbackBuffer(data);
                     if ( (mDraw == null) || mFinished )
                         return;
-
                     if (mDraw.mYUVData == null) {
-                        // Initialize the draw-on-top companion
                         Camera.Parameters params = camera.getParameters();
                         mDraw.mImageWidth = params.getPreviewSize().width;
                         mDraw.mImageHeight = params.getPreviewSize().height;
@@ -785,7 +959,6 @@
                         mDraw.mYUVData = new byte[data.length];
                     }
 
-                    // Pass YUV data to draw-on-top companion
                     System.arraycopy(data, 0, mDraw.mYUVData, 0, data.length);
                     mDraw.invalidate();
                 }
@@ -808,11 +981,7 @@
         }
     }
 
-    //SurfaceView callback
     public void surfaceDestroyed(SurfaceHolder holder) {
-        // Surface will be destroyed when we return, so stop the preview.
-        // Because the CameraDevice object is not a shared resource, it's very
-        // important to release it when the activity is paused.
         mFinished = true;
         if (mCamera != null) {
             mCamera.setPreviewCallback(null);
@@ -822,31 +991,23 @@
         }
     }
 
-    //SurfaceView callback, configuring camera
     public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
         if (mCamera == null) return;
 
-        // Now that the size is known, set up the camera parameters and begin
-        // the preview.
         Camera.Parameters parameters = mCamera.getParameters();
 
-        //Keep uncommented to work correctly on phones:
-        //This is an undocumented although widely known feature
-		/**/
         if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
             parameters.set("orientation", "portrait");
-            mCamera.setDisplayOrientation(90); // For Android 2.2 and above
+            mCamera.setDisplayOrientation(90);
             mDraw.rotated = true;
         } else {
             parameters.set("orientation", "landscape");
-            mCamera.setDisplayOrientation(0); // For Android 2.2 and above
+            mCamera.setDisplayOrientation(0);
         }
-		/**/
-
-        // choose preview size closer to 640x480 for optimal performance
         List<Camera.Size> supportedSizes = parameters.getSupportedPreviewSizes();
         int width = 0;
         int height = 0;
+        System.out.println("surfaceChanged");
         for (Camera.Size s: supportedSizes) {
             if ((width - 640)*(width - 640) + (height - 480)*(height - 480) >
                     (s.width - 640)*(s.width - 640) + (s.height - 480)*(s.height - 480)) {
@@ -855,12 +1016,10 @@
             }
         }
 
-        //try to set preferred parameters
         try {
             if (width*height > 0) {
                 parameters.setPreviewSize(width, height);
             }
-            //parameters.setPreviewFrameRate(10);
             parameters.setSceneMode(Camera.Parameters.SCENE_MODE_PORTRAIT);
             parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
             mCamera.setParameters(parameters);
@@ -884,5 +1043,6 @@
             this.invalidate();
         }
     }
-} // end of Preview class
+
+}
 

--
Gitblit v1.8.0