vamsiampolu

CameraActivity

Dec 25th, 2013
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.01 KB | None | 0 0
  1. package com.blutechnologies.scancard;
  2.  
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7.  
  8. import android.annotation.TargetApi;
  9. import android.app.Activity;
  10. import android.content.Context;
  11. import android.content.Intent;
  12. import android.graphics.Bitmap;
  13. import android.graphics.BitmapFactory;
  14. import android.graphics.Matrix;
  15. import android.hardware.Camera;
  16. import android.hardware.Camera.AutoFocusCallback;
  17. import android.hardware.Camera.CameraInfo;
  18. import android.hardware.Camera.Parameters;
  19. import android.hardware.Camera.PictureCallback;
  20. import android.hardware.Sensor;
  21. import android.hardware.SensorEvent;
  22. import android.hardware.SensorEventListener;
  23. import android.hardware.SensorManager;
  24. import android.media.ExifInterface;
  25. import android.os.Build;
  26. import android.os.Bundle;
  27. import android.os.Debug;
  28. import android.os.Environment;
  29. import android.os.Handler;
  30. import android.os.Message;
  31. import android.support.v4.app.FragmentActivity;
  32. import android.util.Log;
  33. import android.view.KeyEvent;
  34. import android.view.OrientationEventListener;
  35. import android.view.Surface;
  36. import android.view.View;
  37. import android.view.Window;
  38. import android.view.WindowManager;
  39. import android.widget.FrameLayout;
  40.  
  41.  
  42.  
  43. @TargetApi(Build.VERSION_CODES.GINGERBREAD)
  44. public class CameraActivity extends FragmentActivity implements SensorEventListener,ShutterButton.ShutterButtonListener,View.OnClickListener,KeyEvent.Callback
  45. {
  46.     //hope new Camera API works
  47.     long sFocusTime;
  48.     long sClickTime;
  49.     long sSensorCallTime;
  50.     static final int FOCUS_NOT_STARTED=1;
  51.     static final int FOCUSING=2;
  52.     static final int FOCUSING_SNAP_ON_FINISH=3;
  53.     static final int FOCUS_SUCCESS=4;
  54.     static final int FOCUS_FAIL=5;
  55.     private int mFocusState=FOCUS_NOT_STARTED;
  56.     static final int CAMERA_IDLE=1;
  57.     static final int SNAPSHOT_IN_PROGRESS=2;
  58.     private int mCameraStatus;
  59.     private boolean isPreviewShowing=false;
  60.     static final String TAG="CameraActivity";
  61.     SensorManager sensorManager;
  62.     Sensor sensor;
  63.     FrameLayout container;
  64.     ShutterButton btn_capture;
  65.     boolean isClicked;
  66.     CameraPreview mPreview;
  67.     Camera mCamera;
  68.     boolean notContinuousFocus=false;
  69.     boolean blurred;
  70.     float mLastX,mLastY,mLastZ;
  71.     String pathName;
  72.    
  73.     private static final int FIRST_TIME_INIT = 1;
  74.     private static final int CLEAR_SCREEN_DELAY = 2;
  75.    
  76.    
  77.     private MyOrientationEventListener mOrientationListener;
  78.     // The device orientation in degrees. Default is unknown.
  79.     private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
  80.     // The orientation compensation for icons and thumbnails.
  81.     private int mOrientationCompensation = 0;
  82.    
  83.     private boolean mPreviewing;
  84.     private boolean mPausing;
  85.     private boolean mFirstTimeInitialized;
  86.    
  87.     @Override
  88.     public void onAccuracyChanged(Sensor event, int accuracy) {
  89.         // TODO Auto-generated method stub
  90.        
  91.     }
  92.  
  93.     @Override
  94.     public void onSensorChanged(SensorEvent event) {
  95.         // TODO Auto-generated method stub
  96.         if(sFocusTime!=0 &&sClickTime==0)
  97.         {  
  98.             sSensorCallTime=System.currentTimeMillis();
  99.             Log.d(TAG,"Sensor call time"+sSensorCallTime);
  100.         }
  101.         if(!isClicked){
  102.             float x=event.values[0];
  103.             float y=event.values[1];
  104.             float z=event.values[2];
  105.             if(mLastX==0)
  106.                 mLastX=x;
  107.             if(mLastY==0)  
  108.                 mLastY=y;
  109.             if(mLastZ==0)
  110.                 mLastZ=z;
  111.            
  112.             float deltaX=x-mLastX;
  113.             float deltaY=y-mLastY;
  114.             float deltaZ=z-mLastZ;
  115.             if(deltaX>2.5 || deltaY>2.5 || deltaZ>2.5)
  116.             {  
  117.                 if(mFocusState!=FOCUSING && mFocusState!=FOCUSING_SNAP_ON_FINISH)
  118.                 {  
  119.                     mFocusState=FOCUS_NOT_STARTED;
  120.                     Log.d(TAG, "Focus called from accelerometer");
  121.                     doFocus(true);
  122.                 }
  123.             }  
  124.                 mLastX=x;
  125.                 mLastY=y;
  126.                 mLastZ=z;
  127.         }
  128.     }  
  129.        
  130.    
  131.     @Override
  132.     public void onCreate(Bundle savedInstanceState)
  133.     {
  134.         super.onCreate(savedInstanceState);
  135.         requestWindowFeature(Window.FEATURE_NO_TITLE);
  136.         setContentView(R.layout.activity_camera);
  137.         sensorManager=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
  138.         sensor=sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
  139.         container=(FrameLayout)findViewById(R.id.container);
  140.         btn_capture=(ShutterButton)findViewById(R.id.btn_capture);
  141.         btn_capture.setShutterButtonListener(this);
  142.         btn_capture.setVisibility(View.VISIBLE);
  143.         btn_capture.setClickable(true);
  144.     }
  145.    
  146.     @Override
  147.     public void onResume()
  148.     {
  149.         if(mFirstTimeInitialized)
  150.             initializeSecondTime();
  151.         else
  152.             initializeFirstTime();
  153.         super.onResume();
  154.         initializeCamera();
  155.         sensorManager.registerListener(this, sensor,SensorManager.SENSOR_DELAY_UI);
  156.     }
  157.    
  158.     private void initializeCamera()
  159.     {
  160.         try
  161.         {
  162.             mCamera=Camera.open();
  163.         }
  164.         catch(Exception ex)
  165.         {
  166.             Log.d(TAG, "Could not open camera");
  167.         }
  168.         mPreview=new CameraPreview(this,mCamera);
  169.         container.addView(mPreview);
  170.         isPreviewShowing=true;
  171.     }
  172.    
  173.     private void autoFocus()
  174.     {
  175.         //Confused about the condition:
  176.         if(mFocusState==FOCUS_NOT_STARTED && isPreviewShowing && mCameraStatus!=SNAPSHOT_IN_PROGRESS)
  177.         {
  178.             mFocusState=FOCUSING;
  179.             mCamera.autoFocus(autoFocusCallback);
  180.         }
  181.     }
  182.    
  183.     private void cancelAutoFocus()
  184.     {
  185.         //Confused about the condition
  186.         if(mCameraStatus==CAMERA_IDLE && (mFocusState==FOCUSING||mFocusState==FOCUS_SUCCESS||mFocusState==FOCUS_FAIL))
  187.         {
  188.             mCamera.cancelAutoFocus();
  189.         }
  190.         mFocusState=FOCUS_NOT_STARTED;
  191.     }
  192.    
  193.     private void doSnap()
  194.     {
  195.         int rotation=0;
  196.          if (mOrientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
  197.              CameraInfo info = new CameraInfo();
  198.              Camera.getCameraInfo(CameraInfo.CAMERA_FACING_BACK, info);
  199.              if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
  200.                  rotation = (info.orientation - mOrientation + 360) % 360;
  201.              } else {  // back-facing camera
  202.                  rotation = (info.orientation + mOrientation) % 360;
  203.              }
  204.          }
  205.          Camera.Parameters params=mCamera.getParameters();
  206.          params.setRotation(rotation);
  207.          mCamera.setParameters(params);
  208.         String mFocusMode=mCamera.getParameters().getFocusMode();
  209.         if(mFocusMode.equals(Parameters.FOCUS_MODE_INFINITY)||mFocusMode.equals(Parameters.FOCUS_MODE_EDOF)||mFocusMode.equals(mFocusMode.equals(Parameters.FOCUS_MODE_FIXED))||mFocusState==FOCUS_SUCCESS||mFocusState==FOCUS_FAIL||mFocusState==FOCUS_NOT_STARTED)
  210.         {
  211.             //take a picture here
  212.             //If the focus was not started,it will go through the focus states if the user holds on to the ShutterButton until the Camera focuses...
  213.             //If it does come to do snap
  214.             mCameraStatus=SNAPSHOT_IN_PROGRESS;
  215.             mCamera.takePicture(null, null, pictureCallback);
  216.         }
  217.         else if(mFocusState==FOCUSING)
  218.             mFocusState=FOCUSING_SNAP_ON_FINISH;
  219.            
  220.     }
  221.    
  222.     private void doFocus(boolean pressed)
  223.     {
  224.         //Pressed is set to true,if ShutterButton is half-pressed
  225.         if(pressed)
  226.             autoFocus();
  227.         else
  228.             cancelAutoFocus();
  229.     }
  230.    
  231.     @Override
  232.     public void onPause()
  233.     {
  234.         mOrientationListener.disable();
  235.         sensorManager.unregisterListener(this);
  236.         isPreviewShowing=false;
  237.         if(mCamera!=null)
  238.         killCamera();
  239.         container.removeAllViews();
  240.         super.onPause();
  241.     }
  242.    
  243.    
  244.     private void killCamera()
  245.     {
  246.         if(mCamera!=null)
  247.         {
  248.             mCamera.cancelAutoFocus();
  249.             mCamera.setPreviewCallback(null);
  250.             mCamera.stopPreview();
  251.             mCamera.release();
  252.             mCamera=null;
  253.         }
  254.     }
  255.    
  256.     AutoFocusCallback autoFocusCallback=new AutoFocusCallback(){
  257.  
  258.         @Override
  259.         public void onAutoFocus(boolean success, Camera camera) {
  260.             // TODO Auto-generated method stub
  261.             Log.d(TAG, "Started focusing");
  262.             if(mFocusState==FOCUSING_SNAP_ON_FINISH)
  263.             {
  264.                 //Take a picture regardless of whether the focus succeeds or fails:
  265.                 if(success)
  266.                     mFocusState=FOCUS_SUCCESS;
  267.                 else
  268.                     mFocusState=FOCUS_FAIL;
  269.                 doSnap();
  270.             }
  271.            
  272.             else if(mFocusState==FOCUSING)
  273.             {
  274.                 if(success)
  275.                     mFocusState=FOCUS_SUCCESS;
  276.                 else
  277.                     mFocusState=FOCUS_FAIL;
  278.             }
  279.            
  280.             else if(mFocusState==FOCUS_NOT_STARTED)
  281.             {
  282.                 Log.d(TAG,"Focus not started,doing nothing");
  283.             }
  284.         }
  285.        
  286.     };
  287.    
  288.     PictureCallback pictureCallback=new PictureCallback()
  289.     {
  290.  
  291.         @Override
  292.         public void onPictureTaken(final byte[] data, Camera camera) {
  293.             // TODO Auto-generated method stub
  294.             Log.d(TAG,"In picture callback");
  295.             mCameraStatus=CAMERA_IDLE;
  296.             String path=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath();
  297.             File dir=new File(path);
  298.             if(!dir.exists())
  299.                 dir.mkdirs();
  300.             String fileName="IMG_"+System.currentTimeMillis()+".jpg";
  301.             pathName=path+File.separator+fileName;
  302.             new Thread()
  303.             {
  304.                 public void run()
  305.                 {
  306.                     try {
  307.                         FileOutputStream fos=new FileOutputStream(pathName);
  308.                         fos.write(data);
  309.                         Log.d(TAG, "Data saved to file successfully");
  310.                     } catch (FileNotFoundException e) {
  311.                         Log.e(TAG, "The output file could not be found",e);
  312.                     } catch (IOException e) {
  313.                         Log.e(TAG, "There was an exception writing from byte[] to file",e);
  314.                     }
  315.                    
  316.                     try {
  317.                         ExifInterface exif=new ExifInterface(pathName.toString());
  318.                         int exifOrientation=exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL);
  319.                         Log.d(TAG,"Orient:"+exifOrientation);
  320.                         int rotate=0;
  321.                         switch(exifOrientation)
  322.                         {
  323.                             case ExifInterface.ORIENTATION_ROTATE_90:
  324.                                 rotate=90;
  325.                                 break;
  326.                             case ExifInterface.ORIENTATION_ROTATE_180:
  327.                                 rotate=180;
  328.                                 break;
  329.                             case ExifInterface.ORIENTATION_ROTATE_270:
  330.                                 rotate=270;
  331.                                 break;
  332.                         }
  333.                         Log.d(TAG,"Rotation:"+rotate);
  334.                         if(rotate!=0)
  335.                         {
  336.                             Bitmap bitmap=BitmapFactory.decodeFile(pathName);
  337.                             int w=bitmap.getWidth();
  338.                             int h=bitmap.getHeight();
  339.                             Matrix mtx=new Matrix();
  340.                             mtx.preRotate(rotate);
  341.                             bitmap=Bitmap.createBitmap(bitmap, 0, 0,w,h,mtx,false);
  342.                             bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
  343.                             FileOutputStream fos;
  344.                             try {
  345.                                 fos = new FileOutputStream(pathName);
  346.                                 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
  347.                             } catch (FileNotFoundException e) {
  348.                                 Log.e(TAG, "Error saving rotated bitmap to file,e");
  349.                             }
  350.                         }
  351.                     }
  352.                     catch(IOException e) {
  353.                         Log.e(TAG,"Rotate or coversion failed:"+e.toString());
  354.                         }
  355.                 }
  356.             }.start();
  357.             Intent intent=new Intent(getBaseContext(),ImagePreviewActivity.class);
  358.             intent.putExtra("pathName", pathName);
  359.             isPreviewShowing=false;
  360.             startActivity(intent);     
  361.         }
  362.     };
  363.     @Override
  364.     public void onShutterButtonFocus(ShutterButton shutterButton,
  365.             boolean pressed) {
  366.         // TODO Auto-generated method stub
  367.         sFocusTime=System.currentTimeMillis();
  368.         Log.d(TAG, "Shutter button focus called "+sFocusTime);
  369.         switch(shutterButton.getId())
  370.         {
  371.             case R.id.btn_capture:
  372.             {  
  373.                 isClicked=pressed;
  374.                 doFocus(pressed);
  375.                 break;
  376.             }  
  377.         }
  378.        
  379.     }
  380.  
  381.     @Override
  382.     public void onShutterButtonClick(ShutterButton shutterButton) {
  383.         // TODO Auto-generated method stub
  384.         Log.d(TAG, "Shutter button click called");
  385.         sClickTime=System.currentTimeMillis();
  386.         Log.d(TAG,"ShutterButtonClick time: "+sClickTime);
  387.         Log.d(TAG,"Time taken to go to click"+((float)(sClickTime-sFocusTime)/1000));
  388.         switch(shutterButton.getId())
  389.         {
  390.             case R.id.btn_capture:
  391.                 doSnap();
  392.                 isClicked=false;
  393.                 break;
  394.         }
  395.        
  396.     }
  397.    
  398.     @Override
  399.     public void onClick(View v) {
  400.         // TODO Auto-generated method stub
  401.         //This assumes that the clicks the screen only if the focus has not been set...
  402.         //This feature is useful in phones where accelerometer delay is unacceptable
  403.         doFocus(true);
  404.     }
  405.  
  406.     @Override
  407.     public boolean onKeyDown(int keyCode,KeyEvent event)
  408.     {
  409.         switch(keyCode)
  410.         {
  411.             case KeyEvent.KEYCODE_BACK:
  412.                 startActivity(new Intent(this,MainActivity.class));
  413.         }
  414.         return false;
  415.     }
  416.  
  417.      private class MainHandler extends Handler {
  418.             @Override
  419.             public void handleMessage(Message msg) {
  420.                 switch (msg.what) {
  421.                    
  422.                 case CLEAR_SCREEN_DELAY: {
  423.                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  424.                     break;
  425.                     }
  426.  
  427.                  case FIRST_TIME_INIT: {
  428.                     initializeFirstTime();
  429.                     break;
  430.                     }
  431.  
  432.                    
  433.                 }
  434.             }
  435.         }
  436.    
  437.      private void initializeFirstTime()
  438.      {
  439.          mOrientationListener = new MyOrientationEventListener(CameraActivity.this);
  440.             mOrientationListener.enable();
  441.             mFirstTimeInitialized = true;
  442.      }
  443.      
  444.      private void initializeSecondTime()
  445.      {
  446.          mOrientationListener.enable();
  447.      }
  448.      
  449.      private class MyOrientationEventListener extends OrientationEventListener {
  450.            
  451.          public MyOrientationEventListener(Context context) {
  452.              super(context);
  453.          }
  454.  
  455.          @Override
  456.          public void onOrientationChanged(int orientation) {
  457.              // We keep the last known orientation. So if the user first orient
  458.              // the camera then point the camera to floor or sky, we still have
  459.              // the correct orientation.
  460.              if (orientation == ORIENTATION_UNKNOWN) return;
  461.                 mOrientation = roundOrientation(orientation);
  462.                 // When the screen is unlocked, display rotation may change. Always
  463.                 // calculate the up-to-date orientationCompensation.
  464.                 int orientationCompensation = mOrientation+ getDisplayRotation(CameraActivity.this);
  465.                 if (mOrientationCompensation != orientationCompensation) {
  466.                     mOrientationCompensation = orientationCompensation;
  467.                 }
  468.          }
  469.           public int roundOrientation(int orientation) {
  470.                 return ((orientation + 45) / 90 * 90) % 360;
  471.             }
  472.          
  473.           public int getDisplayRotation(Activity activity) {
  474.                 int rotation = activity.getWindowManager().getDefaultDisplay()
  475.                         .getRotation();
  476.                 switch (rotation) {
  477.                     case Surface.ROTATION_0: return 0;
  478.                     case Surface.ROTATION_90: return 90;
  479.                     case Surface.ROTATION_180: return 180;
  480.                     case Surface.ROTATION_270: return 270;
  481.                 }
  482.                 return 0;
  483.             }
  484.  
  485.      }
  486.      
  487. }
Advertisement
Add Comment
Please, Sign In to add comment