在sdk中找到/sdk/docs/guide/topics/media/camera.html#custom-camera,里面有详细的api参考

在清单文件中添加相应的权限:

    <uses-permission android:name="android.permission.CAMERA" /><uses-feature android:name="android.hardware.camera" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.RECORD_AUDIO" />

按照官方文档,分为下面几步:

  • Detect and Access Camera - Create code to check for the existence of cameras and request access.
  • Create a Preview Class - Create a camera preview class that extends SurfaceView and implements theSurfaceHolder interface. This class previews the live images from the camera.
  • Build a Preview Layout - Once you have the camera preview class, create a view layout that incorporates the preview and the user interface controls you want.
  • Setup Listeners for Capture - Connect listeners for your interface controls to start image or video capture in response to user actions, such as pressing a button.
  • Capture and Save Files - Setup the code for capturing pictures or videos and saving the output.
  • Release the Camera - After using the camera, your application must properly release it for use by other applications.

接下来分别实现:

1、检查设备是否有照相机

    /** 检查设备是否存在照相机 */private boolean checkCameraHardware(Context context) {if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){// this device has a camerareturn true;} else {// no camera on this devicereturn false;}}

2、得到一个照相机

 /** 一种安全的方式获取Cameer对象的实例. */public static Camera getCameraInstance(){Camera c = null;try {c = Camera.open(); // attempt to get a Camera instance
        }catch (Exception e){// Camera is not available (in use or does not exist)
        }return c; // returns null if camera is unavailable}

3、新建一个名为CameraPreview的类

package com.wuyudong.mycamera;import java.io.IOException;import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implementsSurfaceHolder.Callback {private static final String TAG = "CameraPreview";private SurfaceHolder mHolder;private Camera mCamera;public CameraPreview(Context context, Camera camera) {super(context);mCamera = camera;// Install a SurfaceHolder.Callback so we get notified when the// underlying surface is created and destroyed.mHolder = getHolder();mHolder.addCallback(this);// deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);}public void surfaceCreated(SurfaceHolder holder) {// The Surface has been created, now tell the camera where to draw the// preview.try {mCamera.setPreviewDisplay(holder);mCamera.startPreview();} catch (IOException e) {Log.d(TAG, "Error setting camera preview: " + e.getMessage());}}public void surfaceDestroyed(SurfaceHolder holder) {// empty. Take care of releasing the Camera preview in your activity.
    }public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {// If your preview can change or rotate, take care of those events here.// Make sure to stop the preview before resizing or reformatting it.if (mHolder.getSurface() == null) {// preview surface does not existreturn;}// stop preview before making changestry {mCamera.stopPreview();} catch (Exception e) {// ignore: tried to stop a non-existent preview
        }// set preview size and make any resize, rotate or// reformatting changes here// start preview with new settingstry {mCamera.setPreviewDisplay(mHolder);mCamera.startPreview();} catch (Exception e) {Log.d(TAG, "Error starting camera preview: " + e.getMessage());}}
}

4、设置一个预览功能的layout,将原来布局文件中的内容替换成下面的代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal"android:layout_width="fill_parent"android:layout_height="fill_parent"><FrameLayoutandroid:id="@+id/camera_preview"android:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_weight="1"/><Buttonandroid:id="@+id/button_capture"android:text="Capture"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"/>
</LinearLayout>

5、在清单文件中加入 android:screenOrientation="landscape" 调整相机为横向拍摄

6、在MainActivity中添加

public class MainActivity extends Activity {private Camera mCamera;private CameraPreview mPreview;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);// Create an instance of CameramCamera = getCameraInstance();// Create our Preview view and set it as the content of our activity.mPreview = new CameraPreview(this, mCamera);FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);preview.addView(mPreview);}
}

7、实现拍摄按钮的功能

(1)添加拍照回调方法

    private PictureCallback mPicture = new PictureCallback() {@Overridepublic void onPictureTaken(byte[] data, Camera camera) {File pictureFile = new File("/sdcard/" + System.currentTimeMillis()+".jpg");try {FileOutputStream fos = new FileOutputStream(pictureFile);fos.write(data);fos.close();} catch (IOException e) {Log.d("TAG", "Error accessing file: " + e.getMessage());}}};

给拍照按钮添加注册事件:

        // Add a listener to the Capture buttonButton captureButton = (Button) findViewById(R.id.button_capture);captureButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// get an image from the cameramCamera.takePicture(null, null, mPicture);}});

完整的代码如下:

package com.wuyudong.mycamera;import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;public class MainActivity extends Activity {private Camera mCamera;private CameraPreview mPreview;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// 创建一个 Camera 的实例mCamera = getCameraInstance();// 创建一个预览界面mPreview = new CameraPreview(this, mCamera);FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);preview.addView(mPreview);// Add a listener to the Capture buttonButton captureButton = (Button) findViewById(R.id.button_capture);captureButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {mCamera.autoFocus(new AutoFocusCallback() {  // 对焦
                        @Overridepublic void onAutoFocus(boolean success, Camera camera) {// get an image from the cameramCamera.takePicture(null, null, mPicture);}});}});}/** 检查设备是否存在照相机 */private boolean checkCameraHardware(Context context) {if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {// this device has a camerareturn true;} else {// no camera on this devicereturn false;}}/** 一种安全的方式获取Cameer对象的实例. */public static Camera getCameraInstance() {Camera c = null;try {c = Camera.open(); // attempt to get a Camera instance} catch (Exception e) {// Camera is not available (in use or does not exist)
        }return c; // returns null if camera is unavailable
    }private PictureCallback mPicture = new PictureCallback() {@Overridepublic void onPictureTaken(byte[] data, Camera camera) {File pictureFile = new File("/sdcard/" + System.currentTimeMillis()+".jpg");try {FileOutputStream fos = new FileOutputStream(pictureFile);fos.write(data);fos.close();} catch (IOException e) {Log.d("TAG", "Error accessing file: " + e.getMessage());}}};protected void onDestory() {if(mCamera != null) {    //释放资源
            mCamera.release();mCamera = null;}}}

转载于:https://www.cnblogs.com/wuyudong/p/5853877.html

Android 创建自己的Camera App相关推荐

  1. Android创建一个简易课程表APP

    文章目录 目标 问题与解决 设计与实现 界面设计 实现与代码 布局文件代码 MainActivity代码 ClassInfo类代码 目标 简单的课程表APP,显示课程,学期以及第几周,效果图如下: 问 ...

  2. android app 短信接收,Android创建简单发送和接收短信应用

    本文实例为大家分享了Android创建发送和接收短信应用的简单实现过程,供大家参考,具体内容如下 一.接收短信 项目的结构如下:一个简单的接收和发送短信的功能 1.定义一个接收短信的广播:当手机接收到 ...

  3. android camera慢动作,motion camera app安卓版

    motion camera app安卓版这是一款可以拍摄慢动作的相机软件,该软件简单实用.功能强大,能够完美运行在安卓系统上,可以在手机上拍出高清的慢动作视频,同时还支持音视频合成剪辑处理等功能,选择 ...

  4. Camera APP 问题集锦

    1.AE trigger & AF trigger同一帧下,precapture在flashback后导致打闪拍照过曝 [DESCRIPTION] AE trigger & AF tr ...

  5. hybird app(混合式app开发)cordova ionic 创建相应平台的app

    hybird app(混合式app开发) 之ionic 框架平台 guide cordova 创建相应平台的app 1. npm install -g cordova //全局安装cordova-cl ...

  6. Android 实现相机(Camera)预览

    CameraX 是一个 Jetpack 库,旨在帮助您更轻松地开发相机应用. 对于新应用,我们建议从 CameraX 开始.它提供一致且易于使用的 API,适用于绝大多数 Android 设备,并向后 ...

  7. Android官方文档之App Components(Common Intents)(转载)

    原文地址:http://blog.csdn.net/vanpersie_9987/article/details/51244558#rd Intent的真正强大之处在于它的隐式Intent,隐式Int ...

  8. Android官方文档之App Components(Common Intents)

    Intent的真正强大之处在于它的隐式Intent,隐式Intent需要配合Intent-filters使用,有关这方面的概念和知识,您可以参考我翻译的官方文档:<Android官方文档之App ...

  9. 简单Android手机APP地图,android最简单手机地图APP(只需5分钟)

    android最简单手机地图APP--只有三部分. 第一部分 首先建立一个MapActivity在setContentView(R.layout.activity_map);中创建一个代码如下. [h ...

最新文章

  1. AI一键去纹身,几秒钟让你看见明星「真面目」
  2. php 百度收录api_php使用百度翻译api示例分享
  3. 使用script命令自动录屏用户操作
  4. VTK:Utilities之WindowModifiedEvent
  5. eclipse jsp没有提示_JSP+Struts2+JDBC+Mysql实现的校园宿舍管理系统
  6. 前后端交互中,返回前端的自定义响应数据结构
  7. mobilenet V1
  8. 有关Silverlight3.0在浏览器外运行的问题
  9. 如何培养客户忠诚:你要的不是会员,而是粉丝!
  10. [转]如何设置opengl结合vc开发绚丽的3D图形---操作详解
  11. “移动办事之城”杭州:超8成个人办理事项凭身份证通办
  12. TOGAF 企业连续系列
  13. 爬了我的微信好友,原来他们是这样的...
  14. icp增值电信业务经营许可证怎么办理
  15. python : folium
  16. XILINX_zynq_详解(2)
  17. Swiper轮播图插件之如何修改前进后退按钮swiper-button-prev和swiper-button-next的默认样式
  18. anyRTC-在线娃娃机
  19. 水果店线上做活动方案,水果店线上运营策划方案
  20. fullCalendar日历,点击添加日程,点击删除日程

热门文章

  1. SQLServer查询最近一天,三天,一周,一月,一季度方法
  2. 装饰模式:Decorator(转自LoveCherry)
  3. 性能分析工具GpProfile
  4. 004 - PHP git
  5. RN环境搭建(Android端)
  6. 记模拟面试日记(更新...)
  7. 零基础带你学习MySQL—分组统计(十二)
  8. 现在的孩子为什么厌学的那么多?孩子厌学了怎么办?
  9. 新媒体增长方法从哪里找?
  10. 赚钱的一大障碍:知道的赚钱门路太多