Android camera打开摄像头、预览

一、activity_main.xml代码:




    

    

二、AndroidManifest.xml代码:



    
    
    

    
        
            
                

                
            

            
        
    

三、MainActivity.java代码:

public class MainActivity extends AppCompatActivity {
    private Camera fCamera;
    private boolean isPreview = false;
    private SurfaceView surfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        surfaceView=findViewById(R.id.surface_view);

        //surfaceView.setVisibility(View.INVISIBLE);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.CAMERA}, 11);
            }
        }

        surfaceView.getLayoutParams().width=720;
        surfaceView.getLayoutParams().height=720;

        SurfaceView mSurfaceView = (SurfaceView) findViewById(R.id.surface_view);
        SurfaceHolder mSurfaceHolder = mSurfaceView.getHolder();

        mSurfaceHolder.setFormat(PixelFormat.TRANSPARENT);

        mSurfaceHolder.addCallback(mSurfaceCallback);
    }

    private SurfaceHolder.Callback mSurfaceCallback = new SurfaceHolder.Callback() {


        @Override
        public void surfaceCreated(SurfaceHolder surfaceHolder) {
            try {
                fCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
                fCamera.setPreviewDisplay(surfaceHolder);
                fCamera.startPreview();
                isPreview = true;
            } catch (IOException e) {
                Log.e("boy", e.toString());
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
            if(fCamera != null){
                if(isPreview){
                    fCamera.stopPreview();
                    fCamera.release();
                }
            }
        }
    };



}

四、运行效果:

Android camera打开摄像头、预览_第1张图片

你可能感兴趣的:(android,android)