help mi with this, im making a aplication that use the camera and flash a qr code but the camera dont reponse i have this code im trying first to see something with the camera and the i will work with the recognition of the QR code any help will be good
public class activity_flashqr_normalscreensize extends Activity implements
SurfaceHolder.Callback {
private Button boton;
private SurfaceView VisorQR;
SurfaceHolder surfaceHolder;
android.hardware.Camera theCamera;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.flashqr_normalscreensize_esp);
boton = (Button)findViewById(R.id.btnfoto);
VisorQR = (SurfaceView)findViewById(R.id.visorqr);
surfaceHolder = VisorQR.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS)
}
public void refreshCamera() {
if (surfaceHolder.getSurface() == null) {
return;
}
try {
theCamera.stopPreview();
}
catch (Exception e) {
}
try {
theCamera.setPreviewDisplay(surfaceHolder);
theCamera.startPreview();
}
catch (Exception e) {
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
theCamera.lock();
theCamera = android.hardware.Camera.open();
}
catch (RuntimeException e) {
System.err.println(e);
return;
}
android.hardware.Camera.Parameters param;
param = theCamera.getParameters();
param.setPreviewSize(350, 250);
theCamera.setParameters(param);
try {
theCamera.setPreviewDisplay(surfaceHolder);
theCamera.startPreview();
}
catch (Exception e) {
System.err.println(e);
return;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
refreshCamera();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
theCamera.stopPreview();
theCamera.release();
theCamera = null;
}
}
i found a good tutorial to achive what i want here
http://www.codepool.biz/how-to-implement-a-simple-barcode-scan-application-on-android.html
also to use the zxing library u need to add this to the build.gradle.app
in dependedencies on android studio
compile 'com.journeyapps:zxing-android-embedded:3.2.0#aar'
compile 'com.google.zxing:core:3.2.1'
Related
hello I am trying to implement recording in my app. I am able to record a video and save it, but the aspect rateo and resolution are completely messed up. How can I tell to register with the highest quality available?
This is my code
public class VideoFragment extends Fragment implements SurfaceHolder.Callback{
private ToggleButton mToggleButton;
private SurfaceHolder mHolder;
private SurfaceView mSurfaceView;
private MediaRecorder mMediaRecorder;
private Camera mCamera;
private boolean mInitSuccesful;
public static VideoFragment newInstance() {
Bundle args = new Bundle();
VideoFragment fragment = new VideoFragment();
fragment.setArguments(args);
return fragment;
}
public VideoFragment(){}
#Override
public void onStart() {
super.onStart();
getActivity().setTitle(R.string.video);
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
shutdown();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_content, container, false);
Button yo = (Button) rootView.findViewById(R.id.pic);
yo.setVisibility(View.GONE);
mSurfaceView = (SurfaceView) rootView.findViewById(R.id.cameraView);
mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mToggleButton = (ToggleButton) rootView.findViewById(R.id.toggleRecordingButton);
mToggleButton.setOnClickListener(new View.OnClickListener() {
#Override
// toggle video recording
public void onClick(View v) {
if (((ToggleButton)v).isChecked())
if(mMediaRecorder == null) {
try {
initRecorder(mHolder.getSurface());
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
mMediaRecorder.start();
}catch (NullPointerException e){
e.printStackTrace();
try {
initRecorder(mHolder.getSurface());
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
else {
mMediaRecorder.stop();
mMediaRecorder.reset();
try {
initRecorder(mHolder.getSurface());
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
return rootView;
}
/* Init the MediaRecorder, the order the methods are called is vital to
* its correct functioning.
*/
private void initRecorder(Surface surface) throws IOException {
// It is very important to unlock the camera before doing setCamera
// or it will results in a black preview
if(mCamera == null) {
mCamera = Camera.open();
mCamera.unlock();
}
if(mMediaRecorder == null)
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setPreviewDisplay(surface);
mMediaRecorder.setCamera(mCamera);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
File file = new File(Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Utils.getVideoFilename());
// "touch" the file
if(!file.exists()) {
File parent = file.getParentFile();
if(parent != null)
if(!parent.exists())
if(!parent.mkdirs())
throw new IOException("Cannot create " +
"parent directories for file: " + file);
file.createNewFile();
}
mMediaRecorder.setOutputFile(file.getAbsolutePath());
// No limit. Don't forget to check the space on disk.
mMediaRecorder.setMaxDuration(-1);
mMediaRecorder.setVideoFrameRate(15);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
// This is thrown if the previous calls are not called with the
// proper order
e.printStackTrace();
}
mInitSuccesful = true;
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if(!mInitSuccesful)
initRecorder(mHolder.getSurface());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
shutdown();
}
private void shutdown() {
// Release MediaRecorder and especially the Camera as it's a shared
// object that can be used by other applications
mMediaRecorder.reset();
mMediaRecorder.release();
mCamera.release();
// once the objects have been released they can't be reused
mMediaRecorder = null;
mCamera = null;
}
}
Thanks
EDIT:
Solution thanks to the accepted answer
CamcorderProfile cpHigh = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
mMediaRecorder.setProfile(cpHigh);
Try using a CamcorderProfile to set all the MediaRecorder resolution and quality settings first; you don't currently set many of the values, such as size. The MediaRecorder will not pay any attention to the dimensions of your SurfaceView, for one.
I know there are some similar subjects connecting to this but I couldn't solve mine. anyway,I am trying to make some front camera with "flash" where I am calling Camera.release only once in the whole activities, when surfaceDestroyed(). so here is my MainActivity:
#SuppressWarnings("deprecation")
public class MainActivity extends AppCompatActivity {
private Camera mCamera = null;
private CameraPreview mCameraView = null;
private int cameraId = 0;
private void addView() {
if (!getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG)
.show();
} else {
cameraId = findFrontFacingCamera();
if (cameraId < 0) {
Toast.makeText(this, "No front facing camera found.",
Toast.LENGTH_LONG).show();
} else {
try {
mCamera = Camera.open(cameraId);
} catch (Exception e) {
Log.d("ERROR", "Failed to get camera: " + e.getMessage());
}
}
}
if (mCamera != null) {
mCameraView = new CameraPreview(this, mCamera);//create a SurfaceView to show camera data
FrameLayout camera_view = (FrameLayout) findViewById(R.id.camera_view);
camera_view.addView(mCameraView);//add the SurfaceView to the layout
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addView();
ImageButton imgCapture = (ImageButton) findViewById(R.id.imgCapture);
imgCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WindowManager.LayoutParams layout = getWindow().getAttributes();
layout.screenBrightness = 1F;
getWindow().setAttributes(layout);
setContentView(R.layout.whitescreen);
new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
if (CameraPreview.safeToTakePicture) {
CameraPreview.safeToTakePicture = false;
mCamera.takePicture(null, null,
new PhotoHandler(getApplicationContext()));
}
setContentView(R.layout.activity_main);
addView();
}
}.start();
}
});
}
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
Log.d("Camera", "Camera found");
cameraId = i;
break;
}
}
return cameraId;
}
}
When pressing the capture button I switch the layout to an empty one(white layout), wait 3 seconds take a picture and then add the camera view again, here is my CameraPreview class:
#SuppressWarnings("deprecation")
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public static boolean safeToTakePicture = false;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
mCamera.setDisplayOrientation(90);
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("ERROR", "Camera error on surfaceCreated " + 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) {
Log.d("ERROR", "Trying the camera and it's not running");
}
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
safeToTakePicture = true;
} catch (IOException e) {
Log.d("ERROR", "Camera error on surfaceChanged " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mCamera.stopPreview();
mCamera.release();
}
}
I get the error Camera is being used after Camera.release was called a lot of times, for example when taking a picture:
07-02 14:49:35.561 19017-19017/davidandguy.com.selfielightcamera E/AndroidRuntime: FATAL EXCEPTION: main
Process: davidandguy.com.selfielightcamera, PID: 19017
java.lang.RuntimeException: Camera is being used after Camera.release() was called
at android.hardware.Camera.native_takePicture(Native Method)
at android.hardware.Camera.takePicture(Camera.java:1523)
at android.hardware.Camera.takePicture(Camera.java:1468)
at davidandguy.com.selfielightcamera.MainActivity$1$1.onFinish(MainActivity.java:65)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Or even when onResume() is called, for example, minimize the activity and then run again. I know I need to put somewhere onPause() and onResume() but I don't know where/how to implement it. thanks
This is really overdue but as I managed to solve a similar problem of mine a minute ago, I thought I'd contribute for the benefit of yourself and anyone else who might be desperately searching Stack.
I cant see your lifecycle code here , but heres what worked for me, surfaceDestroyed was empty in my case
Firstly, the cameraPreview
public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {
try {
this.mCamera.setPreviewDisplay(surfaceHolder);
this.mCamera.startPreview();
} catch (Exception e) {
}
}
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
//TODO we need this here too because on SurfaceCreated we always need to open the camera, in case its released
this.mCamera.setPreviewDisplay(surfaceHolder);
this.mCamera.setDisplayOrientation(90);
//this.mCamera.startPreview();
} catch (IOException e) {
}
}
Next, the CameraActivity
#Override
public void onResume() {
super.onResume();
try{
mCamera = openFrontFacingCameraGingerbread();
// Add to Framelayout
this.mCameraPreview = new CameraPreview(this, this.mCamera);
mImage.removeAllViews();
this.mImage.addView(this.mCameraPreview);
}catch (RuntimeException ex){
}
}
#Override
public void onPause() {
super.onPause();
captureButton.setText("Begin Capture");
if(CameraActivity.this.timer !=null) {
CameraActivity.this.timer.cancel();
CameraActivity.this.timer.purge();
CameraActivity.this.timer = null;
}
if (mCamera != null) {
mCamera.setPreviewCallback(null);
mCameraPreview.getHolder().removeCallback(mCameraPreview);
mCamera.release();
mCamera = null;
}
}
#Override
protected void onDestroy(){
super.onDestroy();
releaseCameraAndPreview();
}
private void releaseCameraAndPreview() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
if(mCameraPreview != null){
mCameraPreview.destroyDrawingCache();
mCameraPreview.mCamera = null;
}
}
I'm being frustrated by something that should very simple: taking a picture using Android's camera API (with no preview). I've been following several answers from stackoverflow, but with no success.
Initially I followed this answer (#sush): How to take pictures from the camera without preview when my app starts?
But the PictureCallback was never called. I then followed this answer (#Alex Cohn):
You correctly found that takePicture() should not be called before startPreview() or immediately after it. (onPictureTaken never called)
Which led me to try three solutions.
Solution 1
The first solution places a callback in SurfaceHolder:
public class TestActivity extends Activity
{
private Camera mCamera;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takeSnapShot();
}
#Override
protected void onPause()
{
clearCamera();
super.onPause();
}
private void takeSnapShot()
{
if (mCamera == null)
{
try { mCamera = Camera.open(); }
catch (Exception e) { e.printStackTrace(); }
SurfaceView surface = (SurfaceView) findViewById(R.id.preview);
surface.getHolder().addCallback(mSurfaceHolderCallback);
try { mCamera.setPreviewDisplay(surface.getHolder()); }
catch (IOException e) { e.printStackTrace(); }
mCamera.startPreview();
}
}
private final SurfaceHolder.Callback mSurfaceHolderCallback = new SurfaceHolder.Callback()
{
#Override
public void surfaceCreated(SurfaceHolder holder)
{
try
{
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
mCamera.takePicture(null, null, mPictureCallback);
}
catch (IOException e) { e.printStackTrace(); }
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
};
private final Camera.PictureCallback mPictureCallback = new Camera.PictureCallback()
{
#Override
public void onPictureTaken(byte[] data, Camera camera)
{
FileOutputStream outStream = null;
try
{
File dir_path =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File pictureFile = new File(dir_path, "snapshot-test.jpg");
outStream = new FileOutputStream(pictureFile);
outStream.write(data);
outStream.close();
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
finally { clearCamera(); }
}
};
private void clearCamera()
{
if (mCamera != null)
{
try
{
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
catch (final Exception e) { e.printStackTrace(); }
}
}
This first solution works if I call takeSnapShot just once. Unfortunately, I can't get mSurfaceHolderCallback to run SurfaceCreated multiple times.
Solution 2
My second solution was to use PreviewCallback. In this solution I've re-used onPause:
public class TestActivity extends Activity
{
private Camera mCamera;
private boolean mReadyToTakePicture;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takeSnapShot();
}
private void takeSnapShot()
{
if (mCamera == null)
{
try { mCamera = Camera.open(); }
catch (Exception e) { e.printStackTrace(); }
mCamera.setPreviewCallback(mRawPreviewCallback);
SurfaceView surface = (SurfaceView) findViewById(R.id.preview);
try { mCamera.setPreviewDisplay(surface.getHolder()); }
catch (IOException e) { e.printStackTrace(); }
mCamera.startPreview();
}
}
private final Camera.PreviewCallback mRawPreviewCallback = new Camera.PreviewCallback()
{
#Override
public void onPreviewFrame(byte [] rawData, Camera camera)
{
int rawDataLength = 0;
if (rawData != null) { rawDataLength = rawData.length; }
if (rawDataLength > 0 && !mReadyToTakePicture)
{
mReadyToTakePicture = true;
mCamera.takePicture(null, null, mPictureCallback);
}
else { mReadyToTakePicture = false; }
}
};
private final Camera.PictureCallback mPictureCallback = new Camera.PictureCallback()
{
#Override
public void onPictureTaken(byte[] data, Camera camera)
{
FileOutputStream outStream = null;
mReadyToTakePicture = false;
try
{
File dir_path =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File pictureFile = new File(dir_path, "snapshot-test.jpg");
outStream = new FileOutputStream(pictureFile);
outStream.write(data);
outStream.close();
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
finally { clearCamera(); }
}
};
private void clearCamera()
{
if (mCamera != null)
{
try
{
mReadyToTakePicture = false;
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
catch (final Exception e) { e.printStackTrace(); }
}
}
}
In this solution both mRawPreviewCallback and mPictureCallback are never called.
Solution 3
My last example is using an AsyncTask that waits for a while before actually taking a picture. Hopefully this would give enough time for the preview to be set. In this solution I've re-used onPause and clearCamera:
public class TestActivity extends Activity
{
private Camera mCamera;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takeSnapShot();
}
private void takeSnapShot()
{
if (mCamera == null)
{
try { mCamera = Camera.open(); }
catch (Exception e) { e.printStackTrace(); }
SurfaceView surface = (SurfaceView) findViewById(R.id.preview);
try { mCamera.setPreviewDisplay(surface.getHolder()); }
catch (IOException e) { e.printStackTrace(); }
mCamera.startPreview();
new CameraTask().execute(mCamera);
}
}
private class CameraTask extends AsyncTask<Camera, Void, Void>
{
protected String doInBackground(Camera... cameras)
{
try { Thread.sleep(1500); } catch (InterruptedException e)
{ e.printStackTrace(); }
mCamera = cameras[0];
mCamera.takePicture(null, null, mPictureCallback);
return mPicturePath;
}
private final Camera.PictureCallback mPictureCallback = new Camera.PictureCallback()
{
#Override
public void onPictureTaken(byte[] data, Camera camera)
{
FileOutputStream outStream = null;
try
{
File dir_path =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File pictureFile = new File(dir_path, "snapshot-test.jpg");
mPicturePath = pictureFile.getAbsolutePath();
outStream = new FileOutputStream(pictureFile);
outStream.write(data);
outStream.close();
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
finally { clearCamera(); }
}
};
}
}
As with solution 2, onPictureTaken is never called.
In all examples the layout of my SurfaceView is as follows (for no preview):
<SurfaceView
android:id="#+id/preview"
android:layout_width="1dp"
android:layout_height="1dp"></SurfaceView>
At this point I'm running out of ideas. My first example was successful in taking one picture, so if I could at least force the app to run surfaceCreated multiple times, it should work. Any ideas?
Ok so I have faced this issue before on gingerbread devices.
Do the following:
mCamera.takePicture(null, null, new Camera.PictureCallback() {
#Override
public void onPictureTaken(final byte[] originalData, Camera camera) {
// logic here
});
instead of:
mCamera.takePicture(null, null,myCallback);
private PictureCallback mPicallback = new PictureCallback(){
};
I'm using this to use android camera:
public class Login extends Activity implements SurfaceHolder.Callback {
public int idCamera(int id) {
if (id == 0) { id = 1; } else { id = 0; }
int tcam = Camera.getNumberOfCameras();
if (tcam == 1) { id = 0; }
return id;
}
public class idCameraV {
public int id;
}
public static class camHolder {
public static SurfaceHolder id;
}
private Camera camera;
private SurfaceView surfaceView;
static String senha2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final idCameraV idCam = new idCameraV();
idCam.id = 0;
camera = Camera.open(idCam.id);
Camera.Parameters parametro = camera.getParameters(); // WORKS OK
parametro.setFlashMode("on"); // WORKS OK
camera.setParameters(parametro); // WORKS OK
surfaceView = (SurfaceView) findViewById(R.id.preview);
surfaceView.getHolder().addCallback(this);
final ImageButton button1 = (ImageButton) findViewById(R.id.bt_camera);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
camera.stopPreview();
camera.release();
idCam.id = idCamera(idCam.id);
camera = Camera.open(idCam.id);
Camera.Parameters parametro = camera.getParameters();
parametro.setFlashMode("on"); // THIS LINE AND ABOVE WORKS. I CAN READ BY GETFLASHMODE
camera.setParameters(parametro); // ERROR IN HERE
camera.startPreview();
try {
camera.setPreviewDisplay(camHolder.id);
} catch (IOException e) {
e.printStackTrace();
}
}
});
final ImageButton button2 = (ImageButton) findViewById(R.id.bt_login);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText senha = (EditText)findViewById(R.id.senha);
senha2 = senha.getText().toString();
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
RelativeLayout aviso = (RelativeLayout) findViewById(R.id.aguarde);
aviso.setVisibility(View.VISIBLE);
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String coordenadas = GPS.coordenadas(locationManager);
String android_id = Secure.getString(getBaseContext().getContentResolver(), Secure.ANDROID_ID);
camera.takePicture(null, null, new TiraFoto(getApplicationContext(), android_id, coordenadas, aviso, connMgr, "LOGIN_", camera));
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if (camera != null) { camera.release(); }
}
#Override
protected void onPause() {
super.onPause();
if (camera != null) { camera.stopPreview(); }
}
#SuppressWarnings("static-access")
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
final camHolder camHolderId = new camHolder();
camHolderId.id = holder;
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (holder.getSurface() != null) {
try {
camera.stopPreview();
} catch (Exception e) {
}
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {}
}
It works ok, but when I do the camera swap, the app freezes. I'm setting the flashmode when I open the camera first time, and it works, but when I do the swap, I get a set parameter error. Where I must set this parameters?
The front camera doesn't support flash mode, maybe the code as below can work
if(idCam.id == 0)
parametro.setFlashMode("on");
According to your question, please refer to the Android Developers: Camera
Basically, you'll need to set the camera parameters inside surfacedChanged method
And here for your information, I copy/paste the related code:
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 exist
return;
}
// stop preview before making changes
try {
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 settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
Please let me know if it works
I have some problem in my code. I must start camera and capture it , so here is my code, and my problem is that camera starting with some strange view, like landscape mode and stretched.
mVideoCaptureView = (SurfaceView) findViewById(R.id.cameraView);
SurfaceHolder videoCaptureViewHolder = mVideoCaptureView.getHolder();
videoCaptureViewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
videoCaptureViewHolder.addCallback(new Callback() {
public void surfaceDestroyed(SurfaceHolder holder) {
}
public void surfaceCreated(SurfaceHolder holder) {
startVideo();
}
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
and the startVideo() function
private void startVideo() {
if(mCamera != null) return;
SurfaceHolder videoCaptureViewHolder = null;
try {
mCamera = Camera.open();
} catch (RuntimeException e) {
Log.e("CameraTest", "Camera Open filed");
return;
}
mCamera.setErrorCallback(new ErrorCallback() {
public void onError(int error, Camera camera) {
}
});
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewFrameRate(30);
mCamera.setParameters(parameters);
if (null != mVideoCaptureView)
videoCaptureViewHolder = mVideoCaptureView.getHolder();
try {
mCamera.setPreviewDisplay(videoCaptureViewHolder);
} catch (Throwable t) {
}
try {
mCamera.startPreview();
} catch (Throwable e) {
mCamera.release();
mCamera = null;
return;
}
}
Also I must add my own buttons , ImageButtons in camera view
Thanks
Regards
sorry for English
There was some function for Camera `camera.setDisplayOrientation(90); I got it from here