0

I'm a beginner in and I want to open the camera and capture picture automatically. My Code:

 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_camera);
     int cameraCount = 0;
     Camera cam = null;
     Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
     cameraCount = Camera.getNumberOfCameras();
     for (int camIdx = 0; camIdx < cameraCount; camIdx++ ){
         Camera.getCameraInfo(camIdx, cameraInfo);
         if(cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT  ){
             try {
                 cam = Camera.open( camIdx );
             } catch (RuntimeException e) {
                 Log.i("Camera failed to open: ", e.getLocalizedMessage());
             }
         }
     }

     SurfaceView surface = new SurfaceView(this);
     try {
         cam.setPreviewDisplay(surface.getHolder());
     }catch(IOException e){
         e.printStackTrace();
     }
}

But when code is run, camera intent does not start and shows me black page,and doesn't take a picture automatically. How can I solve that?thanks.

Abhishek
  • 2,925
  • 4
  • 34
  • 59
behzad razzaqi
  • 1,503
  • 2
  • 18
  • 33

3 Answers3

2
File cDir = getExternalFilesDir(null);
cDir.mkdir();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String mPhotoresultingFile = new File(cDir.toString()+ "/image.jpg");
Uri uriSavedImage = Uri.fromFile(mPhotoresultingFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,uriSavedImage);
startActivityForResult(cameraIntent, 1888);

add onActivityResult

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        try {
            if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {

                if (mPhotoresultingFile.exists()) {
                    Bitmap photo = BitmapFactory.decodeFile(mPhotoresultingFile
                            .getPath());

                    ExifInterface exif = new ExifInterface(
                            mPhotoresultingFile.getPath());

                    int orientation = exif.getAttributeInt(
                            ExifInterface.TAG_ORIENTATION, 1);
                    Matrix matrix = new Matrix();
                    if (orientation == 6) {
                        matrix.postRotate(90);
                    } else if (orientation == 3) {
                        matrix.postRotate(180);
                    } else if (orientation == 8) {
                        matrix.postRotate(270);
                    }
                    photo = Bitmap.createBitmap(photo, 0, 0, photo.getWidth(),
                            photo.getHeight(), matrix, true);
                    //If you want to delete the captured photo from the gallery 
                    mPhotoresultingFile.delete();


                    }
                }
            }
        } catch (Exception e) {

            e.printStackTrace();
        }

    }

And add Camers Uses Permission in your manifest file.

<uses-permission android:name="android.permission.CAMERA"></uses-permission>
Arun PS
  • 4,610
  • 6
  • 41
  • 56
0

you can try to open back camera by changing your code to, cam = Camera.open( 0 );

Use below complete code for your project, code include pinch zoom camera as well as rotation features !

public class RecordLiveVideo extends Activity implements SurfaceHolder.Callback
{

    private Camera camera;
    private SurfaceView surfaceView;
    Button btn_record, btn_rotate;
    TextView tv_timer;

    MediaRecorder mediaRecorder;

    int temp_for_start_stop_button = 0;

    long start_time;

    static Boolean has_front_camera;

    int current_camera = 0;

    int recording_degree;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recordlivevideo);

        InitCamera(0);

        btn_record = (Button) findViewById(R.id.btn_record);
        tv_timer = (TextView) findViewById(R.id.tv_timer);
        tv_timer.setVisibility(View.GONE);

        btn_rotate = (Button) findViewById(R.id.btn_rotate);

        int n = Camera.getNumberOfCameras();

        if (n > 1)
        {
            has_front_camera = true;
        }
        else
        {
            has_front_camera = false;
            btn_rotate.setBackground(getResources().getDrawable(R.drawable.rotation_close));
        }

        btn_rotate.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub

                if (has_front_camera == true)
                {
                    camera.stopPreview();
                    camera.release();
                    camera = null;

                    if (current_camera == 0)
                    {
                        //start front
                        //recording_degree = 270;
                        current_camera = 1;
                        InitCamera(1);
                    }
                    else
                    {
                        //start back
                        //recording_degree = degree;
                        current_camera = 0;
                        InitCamera(0);
                    }

                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Device has not front camera !", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn_record.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                if (temp_for_start_stop_button == 0)
                {
                    if (startRecording())
                    {
                        tv_timer.setVisibility(View.VISIBLE);
                        tv_timer.setText("0 : 0");
                        temp_for_start_stop_button = 1;

                        btn_record.setBackground(getResources().getDrawable(R.drawable.stop_camera));

                        start_time = System.currentTimeMillis();
                        show_current_time();
                    }

                }
                else
                {
                    tv_timer.setVisibility(View.GONE);

                    temp_for_start_stop_button = 0;

                    btn_record.setBackground(getResources().getDrawable(R.drawable.camera));

                    mediaRecorder.stop();
                    mediaRecorder.reset();
                    mediaRecorder.release();

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
                    {
                        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri contentUri = Uri.fromFile(new File(uniqueOutFile));
                        mediaScanIntent.setData(contentUri);
                        RecordLiveVideo.this.sendBroadcast(mediaScanIntent);
                    }
                    else
                    {
                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
                    }

                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                }

            }
        });

    }

    void InitCamera(int n)
    {
        surfaceView = (SurfaceView) findViewById(R.id.preview);
        surfaceView.getHolder().addCallback(this);
        try
        {
            camera = Camera.open(n);

            Camera.Parameters parametro = camera.getParameters();

            parametro.setColorEffect(Camera.Parameters.EFFECT_MONO);

            parametro.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);

            camera.setParameters(parametro);

            setCameraDisplayOrientation(RecordLiveVideo.this, n, camera);

            camera.setPreviewDisplay(surfaceView.getHolder());

            camera.startPreview();
        }
        catch (final Exception e)
        {

            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();

            camera.release();
            camera = null;
        }

    }

    void show_current_time()
    {

        Handler handler = new Handler();
        handler.postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
                long duration = (int) ((System.currentTimeMillis() - start_time) / 1000);

                int min = 00;
                int sec = 00;

                min = (int) duration / 60;
                sec = (int) (duration % 60);

                //Log.e("MAYUR", "" + min + " : " + sec);

                if (temp_for_start_stop_button == 1)
                {
                    tv_timer.setText("" + min + " : " + sec);
                    show_current_time();
                }

            }

        }, 1000);
    }

    int degree;

    //int result;

    public void setCameraDisplayOrientation(Activity activity, int cameraId, android.hardware.Camera camera)
    {
        android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(cameraId, info);
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        int degrees = 0;
        switch (rotation)
        {
            case Surface.ROTATION_0:

                degrees = 0;
                break;
            case Surface.ROTATION_90:

                degrees = 90;
                break;
            case Surface.ROTATION_180:

                degrees = 180;
                break;
            case Surface.ROTATION_270:

                degrees = 270;
                break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT)
        {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360; // compensate the mirror
            if (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270)
                degree = result;
            else
                degree = result + 180;
        }
        else
        { // back-facing
            result = (info.orientation - degrees + 360) % 360;
            degree = result;
        }

        camera.setDisplayOrientation(result);
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        if (camera != null)
        {
            camera.release();
        }
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        if (camera != null)
        {
            try
            {
                camera.stopPreview();
            }
            catch (Exception e)
            {
                // TODO: handle exception
            }

        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder)
    {
        try
        {
            camera.setPreviewDisplay(holder);
            //camera.startPreview();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

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

        if (holder.getSurface() == null)
        {
            // preview surface does not exist
            return;
        }

        if (holder.getSurface() != null)
        {
            try
            {
                camera.stopPreview();
            }
            catch (Exception e)
            {
            }
            try
            {
                camera.setPreviewDisplay(holder);
                camera.startPreview();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder)
    {
    }

    String uniqueOutFile = null;

    public boolean startRecording()
    {
        try
        {

            if (degree == 90 || degree == 270)
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            else
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

            //camera.setDisplayOrientation(degree);

            camera.unlock();

            mediaRecorder = new MediaRecorder();
            mediaRecorder.setOnErrorListener(new MediaRecorder.OnErrorListener()
            {

                @Override
                public void onError(MediaRecorder mr, int what, int extra)
                {
                    Log.i("mayur", "Error");
                }
            });

            mediaRecorder.setCamera(camera);
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
            mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);

            uniqueOutFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/VideoEffect/VideoEffect_Camera_" + System.currentTimeMillis() + ".mp4";
            File outFile = new File(uniqueOutFile);
            if (outFile.exists())
            {
                outFile.delete();
            }

            mediaRecorder.setOutputFile(uniqueOutFile);
            mediaRecorder.setVideoFrameRate(30);
            mediaRecorder.setVideoEncodingBitRate(3000000);
            mediaRecorder.setVideoSize(640, 480);

            //mediaRecorder.setPreviewDisplay(surfaceView.getHolder().getSurface());
            mediaRecorder.setOrientationHint(degree);
            mediaRecorder.prepare();
            mediaRecorder.start();

            return true;
        }
        catch (Exception e)
        {
            camera.lock();
            return false;
        }

    }

    private float mDist;

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        // Get the pointer ID
        Camera.Parameters params = camera.getParameters();
        int action = event.getAction();

        if (event.getPointerCount() > 1)
        {
            // handle multi-touch events
            if (action == MotionEvent.ACTION_POINTER_DOWN)
            {
                mDist = getFingerSpacing(event);
            }
            else if (action == MotionEvent.ACTION_MOVE && params.isZoomSupported())
            {
                camera.cancelAutoFocus();
                handleZoom(event, params);
            }
        }
        else
        {
            // handle single touch events
            if (action == MotionEvent.ACTION_UP)
            {
                handleFocus(event, params);
            }
        }
        return true;
    }

    private void handleZoom(MotionEvent event, Camera.Parameters params)
    {
        int maxZoom = params.getMaxZoom();
        int zoom = params.getZoom();
        float newDist = getFingerSpacing(event);
        if (newDist > mDist)
        {
            //zoom in
            if (zoom < maxZoom - 1)
                zoom += 2;
        }
        else if (newDist < mDist)
        {
            //zoom out
            if (zoom > 1)
                zoom -= 2;
        }
        mDist = newDist;
        params.setZoom(zoom);
        camera.setParameters(params);
    }

    public void handleFocus(MotionEvent event, Camera.Parameters params)
    {
        //int pointerId = event.getPointerId(0);
        //int pointerIndex = event.findPointerIndex(pointerId);
        // Get the pointer's current position
        //      float x = event.getX(pointerIndex);
        //      float y = event.getY(pointerIndex);

        List<String> supportedFocusModes = params.getSupportedFocusModes();
        if (supportedFocusModes != null && supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO))
        {
            camera.autoFocus(new Camera.AutoFocusCallback()
            {
                @Override
                public void onAutoFocus(boolean b, Camera camera)
                {
                    // currently set to auto-focus on single touch
                }
            });
        }
    }

    /** Determine the space between the first two fingers */
    private float getFingerSpacing(MotionEvent event)
    {
        // ...
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return FloatMath.sqrt(x * x + y * y);
    }

    @Override
    public void onBackPressed()
    {
        // TODO Auto-generated method stub
        super.onBackPressed();
        finish();
    }
}

Enjoy !!

Mayur R. Amipara
  • 1,223
  • 1
  • 11
  • 32
0

Make sure you have defined the following permission:

 <uses-permission android:name="android.permission.CAMERA" />

and also:

 <uses-feature android:name="android.hardware.camera" />
 <uses-feature android:name="android.hardware.camera.autofocus" />
 <uses-feature android:name="android.hardware.camera.flash" />

defined in your AndroidManifest.xml

kgandroid
  • 5,507
  • 5
  • 39
  • 69