码迷,mamicode.com
首页 > 移动开发 > 详细

Android下相机的调用

时间:2015-09-12 17:35:32      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

Android下相机的调用

      Android下相机的调用分别为调用系统相机和Building a Camera App两种用法;

一、调用系统相机

1.MainActivity.java文件

 1 package com.example.takephoto;
 2 
 3 import java.io.File;
 4 
 5 import android.net.Uri;
 6 import android.os.Bundle;
 7 import android.provider.MediaStore;
 8 import android.app.Activity;
 9 import android.content.Intent;
10 import android.view.Menu;
11 import android.view.View;
12 import android.view.View.OnClickListener;
13 import android.widget.Button;
14 import android.media.*;
15 
16 public class MainActivity extends Activity {
17     private Button button;
18     
19 
20     @Override
21     protected void onCreate(Bundle savedInstanceState) {
22         super.onCreate(savedInstanceState);
23         setContentView(R.layout.activity_main);
24         
25         button=(Button)findViewById(R.id.button1);
26         button.setOnClickListener(new View.OnClickListener() {
27             
28             @Override
29             public void onClick(View v) {
30                 // TODO 自动生成的方法存根
31                 Intent intent=new Intent();
32                 intent.setAction("android.media.action.IMAGE_CAPTURE");
33                 intent.addCategory("android.intent.category.DEFAULT");
34                 File file=new File("/sdcard/0000image.jpg");
35                 Uri uri=Uri.fromFile(file);
36                 intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
37                 startActivity(intent);
38             }
39         });
40         
41     }
42 
43     @Override
44     public boolean onCreateOptionsMenu(Menu menu) {
45         // Inflate the menu; this adds items to the action bar if it is present.
46         getMenuInflater().inflate(R.menu.main, menu);
47         return true;
48     }
49 }

2.activity_main.xml布局文件

 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="wrap_content"
 5     android:paddingBottom="@dimen/activity_vertical_margin"
 6     android:paddingLeft="@dimen/activity_horizontal_margin"
 7     android:paddingRight="@dimen/activity_horizontal_margin"
 8     android:paddingTop="@dimen/activity_vertical_margin"
 9     tools:context=".MainActivity" >
10 
11     <Button
12         android:id="@+id/button1"
13         android:layout_width="match_parent"
14         android:layout_height="wrap_content"
15         android:layout_alignParentLeft="true"
16         android:layout_alignParentTop="true"
17         android:layout_marginLeft="73dp"
18         android:text="拍照" />
19    
20 </RelativeLayout>

3.AndroidManifest.xml文件

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="com.example.takephoto"
 4     android:versionCode="1"
 5     android:versionName="1.0" >
 6 
 7     <uses-sdk
 8         android:minSdkVersion="8"
 9         android:targetSdkVersion="18" />
10 
11     <application
12         android:allowBackup="true"
13         android:icon="@drawable/ic_launcher"
14         android:label="@string/app_name"
15         android:theme="@style/AppTheme" >
16         <activity
17             android:name="com.example.takephoto.MainActivity"
18             android:label="@string/app_name" >
19             <intent-filter>
20                 <action android:name="android.intent.action.MAIN" />
21 
22                 <category android:name="android.intent.category.LAUNCHER" />
23             </intent-filter>
24         </activity>
25     </application>
26 
27 </manifest>

4.注:因为是调用的系统摄像头进行拍照,系统相机可以自由获取本地文件的存储权限,所以无需在声明权限。

二、Building a Camera App

1.MainActivity.java文件

  1 package com.example.takemyphoto;
  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.os.Bundle;
  9 import android.app.Activity;
 10 import android.content.Context;
 11 import android.content.pm.PackageManager;
 12 import android.hardware.Camera;
 13 import android.hardware.Camera.AutoFocusCallback;
 14 import android.hardware.Camera.PictureCallback;
 15 import android.util.Log;
 16 import android.view.Menu;
 17 import android.view.View;
 18 import android.widget.Button;
 19 import android.widget.FrameLayout;
 20 
 21 public class MainActivity extends Activity {
 22     private Camera mCamera;
 23     private CreamPrivew mPreview;
 24 
 25     @Override
 26     protected void onCreate(Bundle savedInstanceState) {
 27         super.onCreate(savedInstanceState);
 28         setContentView(R.layout.activity_main);
 29         
 30      // Create an instance of Camera
 31         mCamera = getCameraInstance();
 32 
 33         // Create our Preview view and set it as the content of our activity.
 34         mPreview = new CreamPrivew(this, mCamera);
 35         FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
 36         preview.addView(mPreview);
 37         
 38      // Add a listener to the Capture button
 39         Button captureButton = (Button) findViewById(R.id.button_capture);
 40         captureButton.setOnClickListener(
 41             new View.OnClickListener() {
 42                 @Override
 43                 public void onClick(View v) {
 44                     // get an image from the camera
 45                     mCamera.autoFocus(new AutoFocusCallback(){
 46 
 47                         @Override
 48                         public void onAutoFocus(boolean succeed, Camera camera) {
 49                             // TODO 自动生成的方法存根
 50                             mCamera.takePicture(null, null, mPicture);
 51                         }
 52                         
 53                     });
 54                     
 55                 }
 56             }
 57         );
 58         
 59     }
 60    
 61         
 62         /** Check if this device has a camera */
 63         private boolean checkCameraHardware(Context context) {
 64             if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
 65                 // this device has a camera
 66                 return true;
 67             } else {
 68                 // no camera on this device
 69                 return false;
 70             }
 71         }
 72         /** A safe way to get an instance of the Camera object. */
 73         public static Camera getCameraInstance(){
 74             Camera c = null;
 75             try {
 76                 c = Camera.open(); // attempt to get a Camera instance,api9之后支持(1),打开前置摄像机
 77             }
 78             catch (Exception e){
 79                 // Camera is not available (in use or does not exist)
 80             }
 81             return c; // returns null if camera is unavailable
 82         }
 83    
 84 
 85 
 86     @Override
 87     public boolean onCreateOptionsMenu(Menu menu) {
 88         // Inflate the menu; this adds items to the action bar if it is present.
 89         getMenuInflater().inflate(R.menu.main, menu);
 90         return true;
 91     }
 92     private PictureCallback mPicture = new PictureCallback() {
 93 
 94         @Override
 95         public void onPictureTaken(byte[] data, Camera camera) {
 96 
 97             File pictureFile = new File("/scard/"+System.currentTimeMillis()+".jpg");
 98 
 99             try {
100                 FileOutputStream fos = new FileOutputStream(pictureFile);
101                 fos.write(data);
102                 fos.close();
103             } catch (FileNotFoundException e) {
104                 Log.d("TAG", "File not found: " + e.getMessage());
105             } catch (IOException e) {
106                 Log.d("TAG", "Error accessing file: " + e.getMessage());
107             }
108         }
109     };
110     public void onDestory(){
111         if(mCamera!=null){
112             mCamera.release();
113             mCamera=null;
114             
115         }
116     }
117 }

2.CreamPrivew.java文件

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

3.activity_main.xml布局文件

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3      android:layout_width="fill_parent"
 4     android:layout_height="fill_parent"  
 5     android:orientation="horizontal"
 6     tools:context=".MainActivity" >
 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   
22 
23 </LinearLayout>

 

4.AndroidManifest.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="com.example.takemyphoto"
 4     android:versionCode="1"
 5     android:versionName="1.0" >
 6     <uses-permission android:name="android.permission.CAMERA" />
 7     <uses-feature android:name="android.hardware.camera" />
 8     <uses-feature android:name="android.hardware.camera" android:required="false" />
 9     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
10     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
11 
12     <uses-sdk
13         android:minSdkVersion="8"
14         android:targetSdkVersion="18" />
15 
16     <application
17         android:allowBackup="true"
18         android:icon="@drawable/ic_launcher"
19         android:label="@string/app_name"
20         android:theme="@style/AppTheme" >
21         <activity
22             android:name="com.example.takemyphoto.MainActivity"
23             android:label="@string/app_name" 
24              android:screenOrientation="landscape">
25             <intent-filter>
26                 <action android:name="android.intent.action.MAIN" />
27 
28                 <category android:name="android.intent.category.LAUNCHER" />
29             </intent-filter>
30         </activity>
31     </application>
32 
33 </manifest>

     相关API网址:http://developer.android.com/guide/topics/media/camera.html

 

Android下相机的调用

标签:

原文地址:http://www.cnblogs.com/chance88/p/4803155.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!