如何使用相机实时Feed作为活动背景?

时间:2013-07-12 12:16:19

标签: android background camera surfaceview live-wallpaper

我正在尝试创建一个应用程序,我需要使用相机实时反馈作为背景。 (我知道这是一个愚蠢的事情,但无法帮助,它是客户的需求)。

我尝试使用SurfaceView进行此操作但到目前为止没有成功。

到目前为止,无论我在Stack Overflow上发现了什么,都有更多的猜测或指示,但是没有实时的例子或代码帮助。如果有人在与像我这样的Stack Overflow用户共享一段代码之前做过这样的话会很棒。

2 个答案:

答案 0 :(得分:7)

看看这里:

  

http://developer.android.com/guide/topics/media/camera.html

您需要制作显示相机预览的活动所需的所有代码。

答案 1 :(得分:2)

package com.example.CameraPreview;

import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;

public class CameraView extends SurfaceView implements SurfaceHolder.Callback {

    private SurfaceHolder mHolder;
    private Camera mCamera;

    public CameraView(Context context) {
        super(context);
        if(checkCameraHardware(context))  {
            mCamera = getCameraInstance();
        }
        mHolder = getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public CameraView(Context context, AttributeSet attrs) {
        super(context, attrs);

        if(checkCameraHardware(context))  {
            mCamera = getCameraInstance();
        }
        mHolder = getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.startPreview();
        } catch (IOException e) {
            Log.d("CameraView", "Error setting camera preview: " + e.getMessage());
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {

        if (mHolder.getSurface() == null){
            return;
        }

        try {
            mCamera.stopPreview();
        } catch (Exception e){

        }
        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();

        } catch (Exception e){
            Log.d("CameraView", "Error starting camera preview: " + e.getMessage());
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

    }

    private boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
            return true;
        } else {
            return false;
        }
    }

    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open();
        }
        catch (Exception e){
        }
        return c;
    }

}