Android開發: 調用Camera API 創建Camera

 

steps to follow to create your own camera using camera API,
 
1. add permission to AndroidManifest.xml to get the camera hardware resource and save picture into SD card,
<uses-permission android:name= "android.permission.CAMERA" />
<uses-permission android:name= "android.permission.WRITE_EXTERNAL_STORAGE" />
 
AndroidManifest.xml
 
  1. <? xml version"1.0" encoding = "utf-8"?> 
  2. < manifest xmlns:android ="http://schemas.android.com/apk/res/android" 
  3.     package"android.study.sample" 
  4.     android:versionCode"1" 
  5.     android:versionName"1.0" > 
  6.  
  7.     <uses-sdk android:minSdkVersion"15" /> 
  8.     <uses-permission android:name"android.permission.CAMERA" /> 
  9.     <uses-permission android:name"android.permission.WRITE_EXTERNAL_STORAGE" /> 
  10.  
  11.     <application 
  12.         android:icon ="@drawable/ic_launcher" 
  13.         android:label ="@string/app_name" > 
  14.         
  15.                < activity android:name =".CameraActivity" 
  16.                         android:label ="@string/app_name" 
  17.                
  18.                         android:screenOrientation ="landscape" > 
  19.                         <!-- configure this activity to use landscape orientation --> 
  20.                
  21.                         < intent-filter> 
  22.                       < action android:name ="android.intent.action.MAIN" /> 
  23.                       < category android:name ="android.intent.category.LAUNCHER" /> 
  24.                   </ intent-filter> 
  25.                </ activity> 
  26.         
  27.     </application > 
  28.  
  29. </ manifest> 

 

2. set a preview layout and button in your camera UI to control camera
res/layout/main.xml
 
  1. <? xml version"1.0" encoding = "utf-8"?> 
  2. < LinearLayout xmlns:android ="http://schemas.android.com/apk/res/android" 
  3.     android:orientation"horizontal" 
  4.     android:layout_width"fill_parent" 
  5.     android:layout_height"fill_parent" 
  6.     > 
  7.   <FrameLayout 
  8.     android:id"@+id/camera_preview" 
  9.     android:layout_width"fill_parent" 
  10.     android:layout_height"fill_parent" 
  11.     android:layout_weight"1" 
  12.     /> 
  13.  
  14.   <Button 
  15.     android:id"@+id/button_capture" 
  16.     android:text"Capture" 
  17.     android:layout_width"wrap_content" 
  18.     android:layout_height"wrap_content" 
  19.     android:layout_gravity"center" 
  20.     /> 
  21. </ LinearLayout> 

 

3.implement your a surfaceView for your own camera to preview the live p_w_picpath before taking a picture
 
android.study.sample.CameraPreview.java
 
  1. package android.study.sample; 
  2.  
  3. import java.io.IOException; 
  4.  
  5. import android.content.Context; 
  6. import android.hardware.Camera; 
  7. import android.util.Log; 
  8. import android.view.SurfaceHolder; 
  9. import android.view.SurfaceView; 
  10.  
  11. /** A basic Camera preview class */ 
  12. public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { 
  13.     private SurfaceHolder mHolder; 
  14.     private Camera mCamera; 
  15.     
  16.     String TAG= "CAMERAAPI"
  17.  
  18.     public CameraPreview(Context context, Camera camera) { 
  19.         super (context); 
  20.         mCamera = camera; 
  21.  
  22.         // Install a SurfaceHolder.Callback so we get notified when the 
  23.         // underlying surface is created and destroyed. 
  24.         mHolder = getHolder(); 
  25.         mHolder.addCallback( this ); 
  26.         // deprecated setting, but required on Android versions prior to 3.0 
  27.         mHolder. setType(SurfaceHolder. SURFACE_TYPE_PUSH_BUFFERS); 
  28.     } 
  29.  
  30.     public void surfaceCreated(SurfaceHolder holder) { 
  31.         // The Surface has been created, now tell the camera where to draw the preview. 
  32.         try { 
  33.             mCamera.setPreviewDisplay(holder); 
  34.             mCamera.startPreview(); 
  35.         } catch (IOException e) { 
  36.             Log. d( TAG, "Error setting camera preview: " + e.getMessage()); 
  37.         } 
  38.     } 
  39.  
  40.     public void surfaceDestroyed(SurfaceHolder holder) { 
  41.         // empty. Take care of releasing the Camera preview in your activity. 
  42.     } 
  43.  
  44.     public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { 
  45.         // If your preview can change or rotate, take care of those events here. 
  46.         // Make sure to stop the preview before resizing or reformatting it. 
  47.  
  48.         if (mHolder .getSurface() == null){ 
  49.           // preview surface does not exist 
  50.           return ; 
  51.         } 
  52.  
  53.         // stop preview before making changes 
  54.         try { 
  55.             mCamera.stopPreview(); 
  56.         } catch (Exception e){ 
  57.           // ignore: tried to stop a non-existent preview 
  58.         } 
  59.  
  60.         // set preview size and make any resize, rotate or 
  61.         // reformatting changes here 
  62.  
  63.         // start preview with new settings 
  64.         try { 
  65.             mCamera.setPreviewDisplay( mHolder); 
  66.             mCamera.startPreview(); 
  67.  
  68.         } catch (Exception e){ 
  69.             Log. d( TAG, "Error starting camera preview: " + e.getMessage()); 
  70.         } 
  71.     } 

 

4.build your CameraActivity to start the camera app 
get an camera available  , add this camera to the surfaceview of the screen layout, listen for the User action, If user click to Copture button, call camera to take a picture, and save p_w_picpath into the SD card, this is implemented by the    PictureCallback method set to Camera.takePicture() 

android.study.sample.CameraActivity.java
 
  1. package android.study.sample; 
  2. import java.io.File; 
  3. import java.io.FileNotFoundException; 
  4. import java.io.FileOutputStream; 
  5. import java.io.IOException; 
  6. import java.text.SimpleDateFormat; 
  7. import java.util.Date; 
  8.  
  9. import android.app.Activity; 
  10. import android.hardware.Camera; 
  11. import android.hardware.Camera.PictureCallback; 
  12. import android.os.Bundle; 
  13. import android.os.Environment; 
  14. import android.study.sample.R.id; 
  15. import android.util.Log; 
  16. import android.view.View; 
  17. import android.widget.Button; 
  18. import android.widget.FrameLayout; 
  19.  
  20.  
  21.  
  22. public class CameraActivity extends Activity { 
  23.         
  24.         
  25.         public static final int MEDIA_TYPE_IMAGE = 1
  26.         public static final int MEDIA_TYPE_VIDEO = 2
  27.  
  28.     private Camera mCamera; 
  29.     private CameraPreview mPreview; 
  30.     String TAG= "CAMERAAPI"
  31.     
  32.  
  33.     @Override 
  34.     public void onCreate(Bundle savedInstanceState) { 
  35.         super .onCreate(savedInstanceState); 
  36.         setContentView(R.layout. main ); 
  37.  
  38.         // Create an instance of Camera 
  39.         mCamera = getCameraInstance(); 
  40.  
  41.         // Create our Preview view and set it as the content of our activity. 
  42.         mPreview = new CameraPreview( this, mCamera); 
  43.         FrameLayout preview = (FrameLayout) findViewById(R.id. camera_preview ); 
  44.         preview.addView( mPreview); 
  45.                
  46.         Button captureButton = (Button) findViewById(id. button_capture ); 
  47.         captureButton.setOnClickListener( new CaptureButtonOnClickListener()); 
  48.     } 
  49.     
  50.        
  51.     public class CaptureButtonOnClickListener implements View.OnClickListener{ 
  52.                public void onClick(View v) { 
  53.                       
  54.                      PictureCallback mPicture = new CameraPictureCallBack(); 
  55.                       mCamera.takePicture( null , null , mPicture); 
  56.               }       
  57.     } 
  58.     /** A safe way to get an instance of the Camera object. */ 
  59.     public static Camera getCameraInstance(){ 
  60.         Camera c = null ; 
  61.         try { 
  62.             c = Camera. open(); // attempt to get a Camera instance 
  63.         } 
  64.         catch (Exception e){ 
  65.             // Camera is not available (in use or does not exist) 
  66.         } 
  67.         return c; // returns null if camera is unavailable 
  68.     } 
  69.     
  70.     
  71.     public class CameraPictureCallBack implements PictureCallback{ 
  72.  
  73.                public void onPictureTaken( byte[] data, Camera camera) { 
  74.  
  75.             File pictureFile = getOutputMediaFile( MEDIA_TYPE_IMAGE); 
  76.             if (pictureFile == null){ 
  77.                 Log. d( TAG, "Error creating media file, check storage permissions!"); 
  78.                 return ; 
  79.             } 
  80.  
  81.             try { 
  82.                 FileOutputStream fos = new FileOutputStream(pictureFile); 
  83.                 fos.write(data); 
  84.                 fos.close(); 
  85.             } catch (FileNotFoundException e) { 
  86.                 Log. d( TAG, "File not found: " + e.getMessage()); 
  87.             } catch (IOException e) { 
  88.                 Log. d( TAG, "Error accessing file: " + e.getMessage()); 
  89.             } 
  90.               }       
  91.     } 
  92.     
  93.         /** Create a File for saving an p_w_picpath or video */ 
  94.         private static File getOutputMediaFile( int type){ 
  95.            // To be safe, you should check that the SDCard is mounted 
  96.            // using Environment.getExternalStorageState() before doing this. 
  97.  
  98.            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory( 
  99.                      Environment. DIRECTORY_PICTURES ), "MyCameraApp" ); 
  100.            // This location works best if you want the created p_w_picpaths to be shared 
  101.            // between applications and persist after your app has been uninstalled. 
  102.  
  103.            // Create the storage directory if it does not exist 
  104.            if (! mediaStorageDir.exists()){ 
  105.                if (! mediaStorageDir.mkdirs()){ 
  106.                    Log. d( "MyCameraApp""failed to create directory" ); 
  107.                    return null ; 
  108.                } 
  109.            } 
  110.  
  111.            // Create a media file name 
  112.            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss" ).format( new Date()); 
  113.            File mediaFile; 
  114.            if (type == MEDIA_TYPE_IMAGE){ 
  115.                mediaFile = new File(mediaStorageDir.getPath() + File. separator + 
  116.                "IMG_" + timeStamp + ".jpg" ); 
  117.            } else if (type == MEDIA_TYPE_VIDEO) { 
  118.                mediaFile = new File(mediaStorageDir.getPath() + File. separator + 
  119.                "VID_" + timeStamp + ".mp4" ); 
  120.            } else { 
  121.                return null ; 
  122.            } 
  123.  
  124.            return mediaFile; 
  125.        } 
  126.         
  127.           @Override 
  128.            protected void onPause() { 
  129.                super .onPause(); 
  130.                releaseCamera();              // release the camera immediately on pause event 
  131.            } 
  132.  
  133.            private void releaseCamera(){ 
  134.                if (mCamera != null){ 
  135.                    mCamera.release();        // release the camera for other applications 
  136.                    mCamera = null ; 
  137.                } 
  138.            } 
  139.     
5. when open the app,  UI display like below ,
 

 
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章