0

Need Help with adding a button or ImageView so i can switch to a front camera please help!!! Can anyone help me out and fast been trying to add it in but i keep getting an error on the switch camera. I tried implementing an intent that was a separate class to front camera but when switching back to the back camera the screen will stay black. I want to implement the front camera in correctly the way it should be please if anyone could help thanks. And if you please can please add the front camera source code into my project if you can thanks.

ImageView cameraFront;

private int width, height;

private int sdkVersion;

private int timeCount = 0;

private int PORTRAIT = 0;

private int PORTRAIT_REV = 1;

private int LANDSCAPE_RIGHT = 2;

private int LANDSCAPE_LEFT = 3;

private SurfaceView surface;

private SurfaceHolder surfaceHolder;

private MediaRecorder videoRecorder;

private Button recordBtn;

private TextView timeView;

private String videoPath;

private Timer autoStopTimer;

private Camera mCamera;

private Camera.Parameters parameters;

private List<Size> supportedSizes = null;

private SensorManager sensorManager = null;

private boolean isRecording = false;

boolean changeOrientation = false;

int mDetected_Orientention = 0;

Tosty toast;




@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);

    try {

        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);

        setContentView(R.layout.video_recorder);

        videoPath = getIntent().getStringExtra("videoPath");

        width = getIntent().getIntExtra("Width", 320);

        height = getIntent().getIntExtra("Height", 240);

        WindowManager mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

        Display mDisplay = mWindowManager.getDefaultDisplay();

        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        toast = new Tosty(VideoRecorder.this);

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

        recordBtn.setOnClickListener(this);

        surface = (SurfaceView) findViewById(R.id.surfaceView);

        surfaceHolder = surface.getHolder();

        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        timeView = (TextView) findViewById(R.id.timeView);

        timeView.setTextColor(Color.WHITE);

        initVideoRecording();

        initView();

        setListener();

    }

    catch (Exception e) {

        // TODO: handle exception

        e.printStackTrace();

    }

}

public void initView() {

    cameraFront = (ImageView) findViewById(R.id.cameraSwitch1);

}

public void setListener() {

    cameraFront.setOnClickListener(this);

}


@Override
protected void onResume() {

    super.onResume();

    (new Thread(new Runnable() {

        @Override
        public void run() {

            try {

                Thread.sleep(100);

            } 

            catch (InterruptedException e) {

                e.printStackTrace();

            }

            try {

                initVideoRecording();

                //finish();

            } 

            catch (Exception e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

        }

    })).start();

}

@Override
public void onDestroy() {

    super.onDestroy();
    // Stop sensorManager

    sensorManager.unregisterListener(VideoRecorder.this);

    if (autoStopTimer != null) {

        autoStopTimer.cancel();

        autoStopTimer.purge();

        autoStopTimer = null;
    }

    try {

        stopVideoRecording();

    } 

    catch (Exception e) {

        // TODO Auto-generated catch block

    }

}

@Override
public void onPause() {

    super.onPause();

    if (autoStopTimer != null) {

        autoStopTimer.cancel();

        autoStopTimer.purge();

        autoStopTimer = null;

    }

    try {

        stopVideoRecording();

    } 
    catch (Exception e) {

        // TODO Auto-generated catch block

    }

}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_BACK) {

        // toast.showToast("Back button is pressed");

        sensorManager.unregisterListener(VideoRecorder.this);

        finish();

        return true;
    } 

    else if (keyCode == KeyEvent.KEYCODE_HOME) {

        try {

            stopVideoRecording();

        }

        catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

    return super.onKeyDown(keyCode, event);
}

public void onBackPressed() {
    startActivity(new Intent(this, VideoPlay.class)
    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
    //overridePendingTransition(R.anim.left_right, R.anim.right_left);
    finish();
    return;
}


@Override
public void onClick(View v) {

    // TODO Auto-generated method stub

    switch (v.getId()) {

    case R.id.cameraSwitch1:



        Intent intent = new Intent(VideoRecorder.this, Cemara.class);

        //intent.putExtra("android.intent.extras.CAMERA_FACING", 1);

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

        //intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

        finish();

        startActivity(intent);

        break;

    }

    if (v == recordBtn) {

        try {

            if (isRecording) {

            if (autoStopTimer != null) {

                autoStopTimer.cancel();

                autoStopTimer.purge();

                autoStopTimer = null;

            }

            try {

                stopVideoRecording();

            }

            catch (Exception e) {

                // TODO Auto-generated catch block

            }

            setResult(RESULT_OK);

            finish();

            } 

            else {

                startVideoRecording();

                autoStopTimer = new Timer();        

                autoStopTimer.schedule(new TimerTask() {

                public void run() {

                    timeCount++;

                    runOnUiThread(new Runnable() {

                        public void run() {

                            timeView.setText(String.format("00:%02d", timeCount));

                            if (timeCount == 31) {

                                try {

                                    stopVideoRecording();

                                } 

                                catch (Exception e) {
                                    // TODO Auto-generated catch block

                                }

                                setResult(RESULT_OK);

                                finish();

                            }

                        }

                    });

                    if (timeCount == 31) {

                        autoStopTimer.cancel();

                        autoStopTimer = null;

                    }

                }

                }, 1000, 1000);

            }

        }

        catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();

        }

    }

}

private void initVideoRecording() {

    try {

        if (videoRecorder != null) {

            videoRecorder.stop();

            videoRecorder.release();

            videoRecorder = null;

        }

        if (mCamera != null) {

            mCamera.reconnect();

            mCamera.stopPreview();

            mCamera.release();

            mCamera = null;

        }

        sdkVersion = Build.VERSION.SDK_INT;

        android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();

        android.hardware.Camera.getCameraInfo(0, info);

        mCamera = Camera.open();

        //parameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);

        //parameters.set("focus-mode", "continuous-video");

        //mCamera.setParameters(parameters);

        // Camera setup is based on the API Camera Preview demo
        mCamera.setPreviewDisplay(surfaceHolder);

        parameters = mCamera.getParameters();

        if (sdkVersion <= 8) {

            supportedSizes = parameters.getSupportedVideoSizes();

        }

        // parameters.setRotation(90);

        mCamera.setParameters(parameters);

        // check the intial orientation depending on rotation
        int rotation = getWindowManager().getDefaultDisplay().getRotation();

        int nCurrentOrientation = _getScreenOrientation();

        if (nCurrentOrientation == Configuration.ORIENTATION_PORTRAIT && rotation == Surface.ROTATION_0) {

            System.out.println("We are in portrait mode");
            // parameters.setRotation(0);

            mCamera.setDisplayOrientation(90);

        } 

        else if (nCurrentOrientation == Configuration.ORIENTATION_LANDSCAPE && rotation == Surface.ROTATION_90) {

            System.out.println("We are in landscape mode");

            // parameters.setRotation(0);

            mCamera.setDisplayOrientation(0);

        } 

        else if (nCurrentOrientation == Configuration.ORIENTATION_LANDSCAPE && rotation == Surface.ROTATION_270) {

            System.out.println("Reverse Landscape Mode");

            mCamera.setDisplayOrientation(180);

        } 

        else if (nCurrentOrientation == Configuration.ORIENTATION_PORTRAIT && rotation == Surface.ROTATION_180) {

            System.out.println("Reverse potrait mode");

            mCamera.setDisplayOrientation(90);

        }

        else

            mCamera.setDisplayOrientation(90);

        mCamera.startPreview();

        mCamera.unlock();

    } 

    catch (Exception e) {

        e.printStackTrace();

    }

}

private void stopVideoRecording() throws Exception {

    try {

    if (videoRecorder != null) {

        videoRecorder.stop();

        videoRecorder.release();

        videoRecorder = null;

    }

    if (mCamera != null) {

        mCamera.reconnect();

        mCamera.stopPreview();

        mCamera.release();

        mCamera = null;

    }

}

    catch (Exception e) {

        // TODO: handle exception

        e.printStackTrace();

    }

}

private void startVideoRecording() {

    try {

    if (videoRecorder == null) {

        videoRecorder = new MediaRecorder();

    }

    videoRecorder.setCamera(mCamera);

    videoRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

    videoRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

    videoRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

    videoRecorder.setAudioEncodingBitRate(128000);

    videoRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);

    videoRecorder.setAudioChannels(1);

    videoRecorder.setAudioSamplingRate(48000);

    if (width == 1280) {

        videoRecorder.setVideoEncodingBitRate(22100000);

    } 

    else if (width == 720) {

        videoRecorder.setVideoEncodingBitRate(3508000);

    } 

    else {

        videoRecorder.setVideoEncodingBitRate(777000);

    }

    videoRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);

    videoRecorder.setVideoFrameRate(30);

    videoRecorder.setVideoSize(width, height);

    videoRecorder.setPreviewDisplay(surfaceHolder.getSurface());

    videoRecorder.setOrientationHint(90);

    if (mDetected_Orientention == PORTRAIT) {

        videoRecorder.setOrientationHint(90);

    } 

    else if (mDetected_Orientention == PORTRAIT_REV) {

        videoRecorder.setOrientationHint(270);

    } 

    else if (mDetected_Orientention == LANDSCAPE_RIGHT) {

        videoRecorder.setOrientationHint(180);

    }

    try {

        videoRecorder.setOutputFile(videoPath);

        videoRecorder.prepare();

        videoRecorder.start();

        isRecording = true;

        recordBtn.setText("STOP");

    } 

    catch (Exception e) {

        Log.e("Video", "Failed to prepare and start video recording", e);

        videoRecorder.release();

        videoRecorder = null;

    }

    }

    catch (Exception e) {

        // TODO: handle exception

        e.printStackTrace();

    }

}

@Override
public void onConfigurationChanged(Configuration newConfig) {

    super.onConfigurationChanged(newConfig);

    try {

    int rotation = getWindowManager().getDefaultDisplay().getRotation();

    int nCurrentOrientation = _getScreenOrientation();

    if (nCurrentOrientation == Configuration.ORIENTATION_PORTRAIT && rotation == Surface.ROTATION_0) {

        System.out.println("We are in portriat mode");

        // parameters.setRotation(0);

        mCamera.setDisplayOrientation(90);

        Log.e("Rotation", "90");

    } 

    else if (nCurrentOrientation == Configuration.ORIENTATION_LANDSCAPE && rotation == Surface.ROTATION_90) {

        System.out.println("We are in landscape mode");

        // parameters.setRotation(0);

        Log.e("Rotation", "0");

        mCamera.setDisplayOrientation(0);

    } 

    else if (nCurrentOrientation == Configuration.ORIENTATION_LANDSCAPE && rotation == Surface.ROTATION_270) {

        System.out.println("Reverse Landscape Mode");

        Log.e("Rotation", "180");

        mCamera.setDisplayOrientation(180);

    } 

    else if (nCurrentOrientation == Configuration.ORIENTATION_PORTRAIT && rotation == Surface.ROTATION_180) {

        System.out.println("Reverse potrait mode");

        Log.e("Rotation", "90");

        mCamera.setDisplayOrientation(90);

    }

    }

    catch (Exception e) {

        // TODO: handle exception

        e.printStackTrace();

    }

    // _doSomeThingWhenChangeOrientation(nCurrentOrientation);

}

private int _getScreenOrientation() {

    int returnOrientation = 0;

    try {

        returnOrientation = getResources().getConfiguration().orientation;

    } 

    catch (Exception e) {

        System.out.println(e.getMessage());

    }

    return returnOrientation;

}

int orientation = -1;

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

    // TODO Auto-generated method stub

}

@Override
public void onSensorChanged(SensorEvent sensorEvent) {

    float x = sensorEvent.values[0];

    float y = sensorEvent.values[1];

    if (x >= -5 && x < 5) {

        if (y > 0) {

            mDetected_Orientention = PORTRAIT;

            //Log.e("X", "PORTRAIT");

        }

        else {

            mDetected_Orientention = PORTRAIT_REV;

            //Log.e("X", "PORTRAIT_REV");

        }

    } 

    else {

        if (x >= -10 && x < -5) {

            //Log.e("X", "LAND_RIGHT");

            mDetected_Orientention = LANDSCAPE_RIGHT;

        } 

        else {

            //Log.e("X", "LEND_LEFT");

            mDetected_Orientention = LANDSCAPE_LEFT;

        }

    }

}

}

Stefan
  • 5,203
  • 8
  • 27
  • 51
  • 1
    would have been faster if you googled for it instead of asking here without doing research. http://www.vogella.com/articles/AndroidCamera/article.html – josephus Apr 29 '14 at 22:58
  • been checking on google can't seem to figure it out without error i seen other people code just wasn't' able to add it into mine without error. – user3587194 Apr 29 '14 at 23:03
  • Its easy to say hey heres a link just like how you did but lets actually see some work with the code actually put into mine. Cmon Josephus Villarey show me your coding skills – user3587194 Apr 29 '14 at 23:04
  • 1
    no, i won't provide you with code. part of my "teach a man how to fish" policy (which i just made up right now and only applies to you). but here are more links for you to enjoy. http://stackoverflow.com/questions/9686203/how-to-launch-front-camera-with-intent http://stackoverflow.com/questions/16869272/android-switch-between-front-and-back-camera http://stackoverflow.com/questions/14545031/trying-to-switch-camera-back-to-front-but-getting-exception/14547030#14547030 http://stackoverflow.com/questions/11246497/android-camera-preview-switch-between-cameras – josephus Apr 29 '14 at 23:15
  • seen all those already and your vogella one. I don't see what the problem is with helping someone out with some code. This whole code is mine from scratch. Just like my App. Just need some help with a front camera implemented and your making it harder than what it is. Like really if you can't help then don't write back at all cuz sending links to someone for coding is pretty pathetic get on my level. – user3587194 Apr 29 '14 at 23:22
  • Ive done all types of coding dealing with AWS uploading videos to buckets and just hard done coding. Never worked with the camera stuff. Just need help been stuck on this for a couple days. I know I'm getting close just need that extra lead to figure it out. – user3587194 Apr 29 '14 at 23:24
  • taking back my "teach a man how to fish" policy, as you sound more and more like someone who's actually tried to solve this. check out the code in my answer. – josephus Apr 30 '14 at 00:45
  • Thanks brotha i really appreciate your help if you ever need any help with Android or IOS let me know and we can partner up and help each other out no problem. – user3587194 Apr 30 '14 at 15:01

1 Answers1

1

This answer is 99% plagiarized from a Commonsware tutorial/code sample. I added a button that switches between front and back camera.

PreviewDemo.java

package com.commonsware.android.camera;

import java.io.IOException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Toast;

public class PreviewDemo extends Activity {

    private static final String TAG = PreviewDemo.class.getSimpleName();
    private SurfaceView preview = null;
    private SurfaceHolder previewHolder = null;
    private Camera camera = null;
    private boolean inPreview = false;
    private boolean cameraConfigured = false;
    int cameraID = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        preview = (SurfaceView) findViewById(R.id.preview);
        previewHolder = preview.getHolder();
        previewHolder.addCallback(surfaceCallback);
        previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @SuppressLint("NewApi")
    @Override
    public void onResume() {
        super.onResume();

        // camera = Camera.open();
        camera = Camera.open(cameraID);
        startPreview();
    }

    @Override
    public void onPause() {
        if (inPreview) {
            camera.stopPreview();
        }

        camera.release();
        camera = null;
        inPreview = false;

        super.onPause();
    }

    private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
        Camera.Size result = null;

        for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
            if (size.width <= width && size.height <= height) {
                if (result == null) {
                    result = size;
                } else {
                    int resultArea = result.width * result.height;
                    int newArea = size.width * size.height;

                    if (newArea > resultArea) {
                        result = size;
                    }
                }
            }
        }

        return (result);
    }

    private void initPreview(int width, int height) {
        if (camera != null && previewHolder.getSurface() != null) {
            try {
                camera.setPreviewDisplay(previewHolder);
            } catch (Throwable t) {
                Log.e("PreviewDemo-surfaceCallback", "Exception in setPreviewDisplay()", t);
                Toast.makeText(PreviewDemo.this, t.getMessage(), Toast.LENGTH_LONG).show();
            }

            if (!cameraConfigured) {
                Camera.Parameters parameters = camera.getParameters();
                Camera.Size size = getBestPreviewSize(width, height, parameters);

                if (size != null) {
                    parameters.setPreviewSize(size.width, size.height);
                    camera.setParameters(parameters);
                    cameraConfigured = true;
                }
            }
        }
    }

    private void startPreview() {
        Log.d(TAG, "start preview called");
        if (cameraConfigured && camera != null) {
            Log.d(TAG, "stuff works");
            camera.startPreview();
            inPreview = true;
        }
    }

    SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
        public void surfaceCreated(SurfaceHolder holder) {
            // no-op -- wait until surfaceChanged()
        }

        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            initPreview(width, height);
            startPreview();
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            // no-op
        }
    };

    @SuppressLint("NewApi")
    public void switchCamera(View view) {
        Log.d(TAG, "switch called");
        if (inPreview) {
            camera.stopPreview();
        }
        camera.release();

        cameraID = (cameraID + 1) % 2;
        camera = Camera.open(cameraID);
        try {
            camera.setPreviewDisplay(previewHolder);
        } catch (IOException e) {
            e.printStackTrace();
        }
        camera.startPreview();
    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <android.view.SurfaceView
        android:id="@+id/preview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </android.view.SurfaceView>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="switch"
        android:layout_alignParentBottom="true"
        android:onClick="switchCamera" />

</RelativeLayout>
josephus
  • 8,284
  • 1
  • 37
  • 57
  • Awesome thanks brotha for the source code it was a huge help and to actually see something like this was better. I actually figured it out by using mCamera = Camera.open(CameraInfo.CAMERA_FACING_FRONT); its a pretty sweet line of code but the only problem is that i got an error when switching back and forth to each camera and the start button to record a video didn't work. Im definitely going to try your code. It looks like a really good example. Wish me luck brotha. – user3587194 Apr 30 '14 at 15:28
  • Damn brotha I'm still failing at this i got the switch to happen but whenever i make the switch from front to back the start button never works anymore. Not exactly sure why its not working. Do you want my xml file to try for yourself. Thanks brotha again for all your help – user3587194 Apr 30 '14 at 17:06
  • ultimate solution...:) – User11 Jul 30 '14 at 13:08