I made a camera preview app for android and everything works fine even when I press the power button to make device asleep, and waking it up again. But when my activity goes to background (like pressing home button) and then it comes to foreground again the program stops.
This is my activity code:
package com.example.campreview;
import com.example.campreview.CameraPreview;
import com.example.campreview.R;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PreviewCallback;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.view.Menu;
import android.view.View;
public class ScanActivity extends Activity {
private CameraPreview CamPrev = null;
private FrameLayout PreviewFrm;
private Camera cam = null;
private Handler atfcs;
private ImageScanner scnr;
private boolean hascam = false;
private boolean prvng = true;
private boolean paused = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
PreviewFrm = (FrameLayout)findViewById(R.id.PreviewFrm);
StartCamera();
if (cam != null) {
hascam = true;
atfcs = new Handler();
CamPrev = new CameraPreview(this, cam, PreviewCB, AutoFocusCB);
PreviewFrm.addView(CamPrev);
}
}
#Override
public void onPause() {
ReleaseCamera();
paused = true;
super.onPause();
}
#Override
public void onResume() {
super.onResume();
if (paused) StartPreview();
}
private boolean StartCamera() {
boolean r = true;
if (cam == null) {
try {
cam = Camera.open();
} catch (Exception e) {
cam = null;
r = false;
}
if (cam != null) {
try {
Camera.Parameters p = cam.getParameters();
if (p.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_AUTO))
p.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
if (p.getSupportedFlashModes().contains(Camera.Parameters.FLASH_MODE_OFF))
p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
if (p.getSupportedPreviewFormats().contains(ImageFormat.NV21))
p.setPreviewFormat(ImageFormat.NV21);
Camera.Size s = null;
int a = 0, b;
for (Camera.Size z : p.getSupportedPreviewSizes()) {
b = z.width * z.height;
if (Math.abs(b - 307200) < Math.abs(a - 307200)) { //640x480 is the best
s = z;
a = b;
}
}
if (a != 0) p.setPreviewSize(s.width, s.height);
cam.setParameters(p);
cam.setDisplayOrientation(90);
if (CamPrev != null) cam.setPreviewDisplay(CamPrev.getHolder());
} catch (Exception e) {
r = false;
cam.release();
cam = null;
}
}
}
return r;
}
private void ReleaseCamera() {
if (cam != null) {
StopPreview();
cam.release();
cam = null;
}
}
public void StartPreview() {
if ((!prvng) & hascam) {
if (StartCamera()) {
cam.setPreviewCallback(PreviewCB);
cam.startPreview();
cam.autoFocus(AutoFocusCB);
prvng = true;
}
}
}
public void StopPreview() {
if (prvng) {
cam.stopPreview();
cam.setPreviewCallback(null);
prvng = false;
}
}
private Runnable DoAutoFocus = new Runnable() {
public void run() {
if (prvng) cam.autoFocus(AutoFocusCB);
}
};
AutoFocusCallback AutoFocusCB = new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
atfcs.postDelayed(DoAutoFocus, 1000);
}
};
PreviewCallback PreviewCB = new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera camera) {
//
}
};
}
And this is the preview code:
package com.example.campreview;
import java.io.IOException;
import android.view.SurfaceView;
import android.view.SurfaceHolder;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.AutoFocusCallback;
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder hldr;
private Camera cam;
private PreviewCallback pcb;
private AutoFocusCallback afcb;
public CameraPreview(Context context, Camera camera, PreviewCallback previewCb, AutoFocusCallback autoFocusCb) {
super(context);
cam = camera;
pcb = previewCb;
afcb = autoFocusCb;
hldr = getHolder();
hldr.addCallback(this);
//hldr.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
try {
cam.setPreviewDisplay(holder);
} catch (IOException e) {
// No Code
}
}
public void surfaceDestroyed(SurfaceHolder holder) {}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (hldr.getSurface() == null) return;
try {
cam.stopPreview();
} catch (Exception e){
// No Code
}
try {
cam.setPreviewDisplay(hldr);
cam.setPreviewCallback(pcb);
cam.startPreview();
cam.autoFocus(afcb);
} catch (Exception e) {
// No Code
}
}
}
Is there any idea how can I solve this problem?
I found the problem. It seems the SurfaceView that is made in program destroys on activity stop. So I replaced it with a SurfaceView in my layout.
package com.example.campreview;
import com.example.campreview.R;
import java.io.IOException;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PreviewCallback;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
public class ScanActivity extends Activity implements OnClickListener {
private SurfaceView PreviewSfc;
private Camera cam = null;
private Handler atfcs;
private boolean hascam = false;
private boolean validdisplay = false;
private boolean prvng = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
PreviewSfc = (SurfaceView)findViewById(R.id.PreviewSfc);
PreviewSfc.getHolder().addCallback(SurfaceCB);
//PreviewSfc.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
StartCamera();
if (cam != null) {
hascam = true;
atfcs = new Handler();
}
}
#Override
public void onPause() {
ReleaseCamera();
super.onPause();
}
#Override
public void onResume() {
super.onResume();
StartPreview();
}
private boolean StartCamera() {
boolean r = true;
if (cam == null) {
try {
cam = Camera.open();
} catch (Exception e) {
cam = null;
r = false;
}
if (cam != null) {
try {
Camera.Parameters p = cam.getParameters();
if (p.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_AUTO))
p.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
if (p.getSupportedFlashModes().contains(Camera.Parameters.FLASH_MODE_OFF))
p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
if (p.getSupportedPreviewFormats().contains(ImageFormat.NV21))
p.setPreviewFormat(ImageFormat.NV21);
Camera.Size s = null;
int a = 0, b;
for (Camera.Size z : p.getSupportedPreviewSizes()) {
b = z.width * z.height;
if (Math.abs(b - 307200) < Math.abs(a - 307200)) { //640x480 is the best
s = z;
a = b;
}
}
if (a != 0) p.setPreviewSize(s.width, s.height);
cam.setParameters(p);
cam.setDisplayOrientation(90);
if (validdisplay) cam.setPreviewDisplay(PreviewSfc.getHolder());
} catch (Exception e) {
r = false;
cam.release();
cam = null;
}
}
}
//if (!r) Error message that failed to start camera
return r;
}
private void ReleaseCamera() {
if (cam != null) {
StopPreview();
cam.release();
cam = null;
}
}
public void StartPreview() {
if ((!prvng) & (hascam) & (validdisplay)) {
if (StartCamera()) {
cam.setPreviewCallback(PreviewCB);
cam.startPreview();
cam.autoFocus(AutoFocusCB);
prvng = true;
}
}
}
public void StopPreview() {
if (prvng) {
cam.stopPreview();
cam.setPreviewCallback(null);
prvng = false;
}
}
private Runnable DoAutoFocus = new Runnable() {
public void run() {
if (prvng) cam.autoFocus(AutoFocusCB);
}
};
AutoFocusCallback AutoFocusCB = new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
atfcs.postDelayed(DoAutoFocus, 1000);
}
};
PreviewCallback PreviewCB = new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera camera) {
//
}
};
SurfaceHolder.Callback SurfaceCB = new SurfaceHolder.Callback() {
public void surfaceCreated(SurfaceHolder holder) {
if (cam != null) {
try {
cam.setPreviewDisplay(holder);
} catch (IOException e) {
// No Code
}
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
validdisplay = true;
StartPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
validdisplay = false;
}
};
}
Related
I have a SurfaceView showing a CameraSource and I want the camera to focus automatically. Also, when the user taps the SurfaceView, I want the camera to focus on the tapped area. The autofocus is already enabled, but the manual focus is not and I dont know how to add that, any tips?
My code so far:
public class MyActivity extends AppCompatActivity {
SurfaceView cameraPreview;
BarcodeDetector barcodeDetector;
CameraSource cameraSource;
final Integer requestCameraPermissionID = 1001;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity_layout);
final int height = getSurfaceViewHeight();
final int width = getSurfaceViewWidth();
cameraPreview = findViewById(R.id.surfaceview_scanner);
barcodeDetector = new BarcodeDetector.Builder(AddScanningActivity.this)
.setBarcodeFormats(Barcode.ALL_FORMATS)
.build();
cameraSource = new CameraSource.Builder(AddScanningActivity.this, barcodeDetector)
.setAutoFocusEnabled(false)
.setRequestedPreviewSize(width, height)
.build();
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
// handle detections
}
});
cameraPreview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// handle manual focus here?
}
});
cameraPreview.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(AddScanningActivity.this,
new String[]{Manifest.permission.CAMERA}, requestCameraPermissionID);
return;
}
try {
cameraSource.start(cameraPreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}, 100);
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
cameraSource.stop();
}
});
}
}
If it is not possible to have autofocus and manual focus in the same SurfaceView, I would rather have manual focus than autofocus.
As you are making barcode app i will suggest you to use FOCUS_MODE_FIXED,
or
FOCUS_MODE_MACRO
package com.example.yaumanualcamera;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Camera;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Size;
import android.view.Surface;
import android.view.TextureView;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
TextureView textureview;
CameraDevice cameraDevice;
String cameraId;
Size imageDimensions;
CaptureRequest.Builder captureRequestBuilder;
CameraCaptureSession cameraSession;
Handler backgroundHandler;
HandlerThread handleThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textureview = (TextureView) findViewById(R.id.texture);
textureview.setSurfaceTextureListener(surfaceTextureListener);
}
TextureView.SurfaceTextureListener surfaceTextureListener = new TextureView.SurfaceTextureListener() {
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
try {
openCamera();
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
};
private void openCamera() throws CameraAccessException {
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
cameraId = cameraManager.getCameraIdList()[0];
CameraCharacteristics cc = cameraManager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = cc.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
imageDimensions = map.getOutputSizes(SurfaceTexture.class)[0];
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
cameraManager.openCamera(cameraId, stateCallback, null);
}
CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(#NonNull CameraDevice camera) {
cameraDevice = camera;
try {
startCameraPreview();
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void onDisconnected(#NonNull CameraDevice camera) {
cameraDevice.close();
}
#Override
public void onError(#NonNull CameraDevice camera, int error) {
cameraDevice.close();
cameraDevice = null;
}
};
private void startCameraPreview() throws CameraAccessException {
SurfaceTexture texture = textureview.getSurfaceTexture();
texture.setDefaultBufferSize(imageDimensions.getWidth(), imageDimensions.getHeight());
Surface surface = new Surface(texture);
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.addTarget(surface);
System.out.println("Focus 1 ====== "+captureRequestBuilder.get(CaptureRequest.LENS_FOCUS_DISTANCE));
cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(#NonNull CameraCaptureSession session) {
if (cameraDevice == null) {
return;
}
cameraSession = session;
try {
updatePreview();
} catch (CameraAccessException e) {
}
}
#Override
public void onConfigureFailed(#NonNull CameraCaptureSession session) {
}
}, null);
}
private void initPreview() {
float valueAF;
valueAF = 10.0f;
captureRequestBuilder.set(CaptureRequest.CONTROL_MODE,CameraMetadata.CONTROL_MODE_AUTO);
captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CameraMetadata.CONTROL_AF_MODE_OFF);
captureRequestBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, valueAF);
}
private void updatePreview() throws CameraAccessException {
if (cameraDevice == null) {
return;
}
initPreview();
System.out.println("Focus 2 ====== "+captureRequestBuilder.get(CaptureRequest.LENS_FOCUS_DISTANCE));
cameraSession.setRepeatingRequest(captureRequestBuilder.build(), null, backgroundHandler);
}
#Override
protected void onResume() {
super.onResume();
startBackgroundThread();
if (textureview.isAvailable()) {
try {
openCamera();
} catch (CameraAccessException e) {
e.printStackTrace();
}
} else {
textureview.setSurfaceTextureListener(surfaceTextureListener);
}
}
private void startBackgroundThread() {
handleThread = new HandlerThread("CAMERA BACKGROUND");
handleThread.start();
backgroundHandler = new Handler(handleThread.getLooper());
}
#Override
protected void onPause() {
try {
stopBackgroundThread();
} catch (InterruptedException e) {
e.printStackTrace();
}
super.onPause();
}
private void stopBackgroundThread() throws InterruptedException {
handleThread.quitSafely();
handleThread.join();
backgroundHandler = null;
handleThread = null;
}
}
I have flashlight apk with two problem.
İf I use camera, camera.params. My apk working with lower versions Android 5. THen if I use camera2 and camera.manager, My app working with Android 5 and higger versions.
I wanna work with Android version 4 and higger, work with all versions.
How can I do this?
Pls help me for this, thanks.
package com.hallac.erdogan.spechflash;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
public class MainActivity extends AppCompatActivity {
ImageButton btnSwitch;
ImageButton flashlight;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Camera.Parameters params;
private CameraManager mCameraManager;
private String mCameraId;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);//full keran ile ilgili ayarlar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,//full keran ile ilgili ayarlar
WindowManager.LayoutParams.FLAG_FULLSCREEN);//full keran ile ilgili ayarlar
setContentView(R.layout.activity_main);
// flash switch button
btnSwitch = (ImageButton) findViewById(R.id.buton);
flashlight=(ImageButton)findViewById(R.id.flashlight);
// First check if device is supporting flashlight or not
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
// get the camera
getCamera();
// displaying button image
toggleButtonImage();
// Switch button click event to toggle flash on/off
btnSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
// turn off flash
turnOffFlash();
} else {
// turn on flash
turnOnFlash();
}
}
});
flashlight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent= new Intent(getBaseContext(),SpeakNow.class);
startActivity(intent);
}
});
}
// Get the camera
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
}
}
}
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
toggleButtonImage();
}
}
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
toggleButtonImage();
}
}
private void toggleButtonImage(){
if(isFlashOn){
btnSwitch.setImageResource(R.drawable.light_on);
}else{
btnSwitch.setImageResource(R.drawable.light_off);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
// on pause turn off the flash
// turnOffFlash();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
// on resume turn on the flash
if(hasFlash)
turnOnFlash();
}
#Override
protected void onStart() {
super.onStart();
// on starting the app get the camera params
getCamera();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
if (camera != null) {
camera.release();
camera = null;
}
Log.d("Camera","Back Pressed");
}
#Override
protected void onStop() {
super.onStop();
// on stop release the camera
// if (camera != null) {
// camera.release();
// camera = null;
// }
}
}
I have a problem in flash led. When I turn on flash after 2 seconds flash led off automatically. I don't know why it's behaving like that. Can anyone have any idea please help me.
public void cameraFlashOn() {
try {
camera = Camera.open();
Parameters params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
camera.setParameters(params);
camera.startPreview();
camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for off the flash i used following code
public void cameraFlashOff() {
try {
camera.stopPreview();
camera.release();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
package com.mkyong.android;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class FlashLightActivity extends Activity {
//flag to detect flash is on or off
private boolean isLighOn = false;
private Camera camera;
private Button button;
#Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.buttonFlashlight);
Context context = this;
PackageManager pm = context.getPackageManager();
// if device support camera?
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Log.e("err", "Device has no camera!");
return;
}
camera = Camera.open();
final Parameters p = camera.getParameters();
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (isLighOn) {
Log.i("info", "torch is turn off!");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLighOn = false;
} else {
Log.i("info", "torch is turn on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isLighOn = true;
}
}
});
}
}
My Application gives error "Unfortunately PhotoComment has stopped" when I am pressing back or home button. But when I am reopening app from task manager it works.
this is my mainactivity.java
package com.cameratag;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity{
private CameraSurfaceView cameraView;
private ImageView imageResult;
private ImageView imageResult2;
private FrameLayout framenew;
private TextView snapPhoto;
private boolean takePicture = true;
private Bitmap image = null;
private String lastPreviewImgPath = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupcamera();
}
public void setupcamera(){
cameraView = new CameraSurfaceView(getApplicationContext());
imageResult = new ImageView(getApplicationContext());
imageResult.setBackgroundColor(Color.GRAY);
framenew = (FrameLayout) findViewById(R.id.frame);
snapPhoto = (TextView) findViewById(R.id.textView1);
framenew.addView(imageResult);
framenew.addView(cameraView);
}
public void captureHandler(View view){
if(takePicture){
cameraView.capture(jpegHandler);
}
else{
takePicture = true;
cameraView.preview();
framenew.bringChildToFront(cameraView);
imageResult.setImageBitmap(null);
snapPhoto.setText("Capture");
}
}
public void zoomMinusHandler(View view){
cameraView.zoomMinus();
}
public void zoomPilusHandler(View view){
cameraView.zoomPilus();
}
public Camera.PictureCallback jpegHandler = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
image = BitmapFactory.decodeByteArray(data, 0, data.length);
imageResult.setImageBitmap(image);
imageResult2 = imageResult;
LayoutParams params = imageResult.getLayoutParams();
params.width = framenew.getWidth();
params.height = framenew.getHeight();
imageResult2.setLayoutParams(params);
//framenew.bringChildToFront(imageResult);
//snapPhoto.setText("Take Picture");
//takePicture = false;
File directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "NNCam");
if (!directory.exists()) {
if (!directory.mkdirs()) {
//Log.e(TAG, "Failed to create storage directory.");
}
}
String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss").format(new Date(System.currentTimeMillis()));
String filename = "/IMG_" + timeStamp + ".jpg";
if(image!=null){
saveImage(directory.getPath(),filename,image);
cameraView.preview();
}
}
};
public void saveImage(String path, String imgname, Bitmap image){
try{
FileOutputStream fos = new FileOutputStream(path+imgname);
BufferedOutputStream stream = new BufferedOutputStream(fos);
image.compress(CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
}
catch(FileNotFoundException e){
}
catch(IOException e){
}
lastPreviewImgPath = path+imgname;
Bitmap bitmap = BitmapFactory.decodeFile(lastPreviewImgPath);
ImageView myImageView = (ImageView)findViewById(R.id.lastPreview);
myImageView.setImageBitmap(bitmap);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
cameraView.release();
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
cameraView.reconnect();
}
#Override
public void onPause() {
super.onPause();
cameraView.release();
}
}
and this is surfaceview class
package com.cameratag;
import java.io.IOException;
import java.util.List;
import android.content.Context;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
public class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{
private Context context;
private SurfaceHolder mHolder;
public Camera camera = null;
public int zoomValue = 0;
public CameraSurfaceView(Context context) {
super(context);
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// TODO Auto-generated constructor stub
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
Camera.Parameters parameters = camera.getParameters();
List<Camera.Size> sizes = parameters.getSupportedPictureSizes();
Camera.Size cs = sizes.get(0);
List<Camera.Size> sizes2 = parameters.getSupportedPreviewSizes();
Camera.Size cs2 = sizes2.get(0);
parameters.setPreviewSize(cs2.width, cs2.height);
parameters.setPictureSize(cs.width, cs.height);
camera.setParameters(parameters);
camera.startPreview();
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
// TODO Auto-generated method stub
camera = Camera.open();
try {
camera.setPreviewDisplay(mHolder);
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
int rrr = 0;
Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();
if(rotation==0)rrr=90;
else if(rotation==1)rrr=0;
else if(rotation==3)rrr=180;
else rrr=270;
camera.setDisplayOrientation(rrr);
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
camera.stopPreview();
camera = null;
}
public void capture(Camera.PictureCallback jpegHandler){
camera.takePicture(null, null, jpegHandler);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int rrr = 0;
Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();
if(rotation==0)rrr=90;
else if(rotation==1)rrr=0;
else if(rotation==3)rrr=180;
else rrr=270;
//camera.stopPreview();
camera.setDisplayOrientation(rrr);
//camera.startPreview();
}
public void preview(){
camera.startPreview();
}
public void reconnect(){
try {
camera.reconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
}
public void zoomMinus() {
Camera.Parameters parameters = camera.getParameters();
// TODO Auto-generated method stub
if(parameters.isZoomSupported()){
if(zoomValue>0){
zoomValue-=2;
parameters.setZoom(zoomValue);
if(parameters.isSmoothZoomSupported()){
camera.startSmoothZoom(zoomValue);
}
else{
camera.setParameters(parameters);
}
}
}
}
public void zoomPilus() {
Camera.Parameters parameters = camera.getParameters();
// TODO Auto-generated method stub
if(parameters.isZoomSupported()){
if(zoomValue<parameters.getMaxZoom()){
zoomValue+=2;
parameters.setZoom(zoomValue);
if(parameters.isSmoothZoomSupported()){
camera.startSmoothZoom(zoomValue);
}
else{
camera.setParameters(parameters);
}
}
}
}
public void release() {
// TODO Auto-generated method stub
camera.setPreviewCallback(null);
camera.stopPreview();
camera.release();
}
}
Please help.
#Override
protected void onPause() {
super.onPause();
// if (inPreview) {
// mCamera.stopPreview();
// }
// mCamera.release();
// mCamera = null;
// inPreview = false;
mCamera.setPreviewCallback(null);
super.onPause();
// mCamera.stopPreview();
}
I was having a similar issue, the trick is to also setup the camera inside of onResume().
The issue was that the app does not call onCreate() every time you go to an activity with the back button, sometimes it simply pauses the activity. onResume() is called whenever the activity returns to the foreground and is a more reliable place to set up the camera.
#Override
protected void onResume()
{
super.onResume();
if( camera == null )
{
camera = Camera.open();
}
}
try to put your release code in try catch block
try{
if (camera != null){
camera.setPreviewCallback(null);
camera.stopPreview();
camera.release();
}
}
I have found the solution for my own. You only need to change surfaceDestroyed method to this.
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
try{
camera.stopPreview();
camera.release();
camera = null;
}
catch(NullPointerException e){
//e.printStackTrace();
}
}
and on onRestoreInstanceState to this.
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
cameraView = null;
setupcamera();
//cameraView.reconnect();
}
When i try to record video from camera which seems with an error prepare failed: -1.
I search lot and I cant get any acceptable answers from anywhere. here is my code below.
I don't know it by parameter? and by unlocking camera. Any one who can it will be grateful.
package com.camara.activity;
import java.io.IOException;
import android.content.Context;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CamcorderView extends SurfaceView implements
SurfaceHolder.Callback {
MediaRecorder recorder;
SurfaceHolder holder;
String outputFile = "/sdcard/default.mp4";
public CamcorderView(Context context, AttributeSet attrs) {
super(context, attrs);
holder = getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
recorder.setVideoSize(480, 320);
recorder.setVideoFrameRate(10);
recorder.setMaxDuration(10000);
}
public void surfaceCreated(SurfaceHolder holder) {
recorder.setOutputFile(outputFile);
recorder.setPreviewDisplay(holder.getSurface());
if (recorder != null) {
try {
recorder.prepare();
} catch (IllegalStateException e) {
Log.e("IllegalStateException", e.toString());
} catch (IOException e) {
Log.e("IOException", e.toString());
}
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
}
public void setOutputFile(String filename) {
outputFile = filename;
recorder.setOutputFile(filename);
}
public void startRecording() {
recorder.start();
}
public void stopRecording() {
recorder.stop();
recorder.release();
}
}
following is the output from the logcat
01-10 17:33:00.450: I/MediaRecorderJNI(14046): prepare: surface=0x243398 (id=1)
01-10 17:33:00.500: E/MediaRecorder(14046): prepare failed: -1
01-10 17:33:00.500: E/IOException(14046): java.io.IOException: prepare failed.
thanks in advance.
Ok I actually found my mistake. Because of course there was a mistake. Actually I wanted to have a preview and recording at the same time, and thought I had to use the object Camera for that. But Actually the MediaRecorder does that by itself using SetDisplayPreview and .... MediaRecord.Prepare :)
I'm in a good mood, so here's all the class ;)
import java.io.File;
import java.io.IOException;
import android.content.Context;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnInfoListener;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.FrameLayout;
public class ModuleVideo implements SurfaceHolder.Callback, OnInfoListener
{
public static final int STATE_NONE = -1;
public static final int STATE_STOPPED = 0;
public static final int STATE_PREVIEW = 1;
public static final int STATE_CAPTURE = 2;
public static final int STATE_RECORDING = 3;
private SurfaceHolder mHolder;
private MediaRecorder mRecorder;
private SurfaceView mCameraView;
private Context mContext;
private FrameLayout mParent;
private int mState;
private boolean mRecording;
public ModuleVideo(Context context, FrameLayout parent)
{
//Initiate the Surface Holder properly
mParent = parent;
mContext = context;
mRecorder = null;
mState = STATE_NONE;
mRecording = false;
}
private void Init()
{
mRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile camcorderProfile_HQ = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
mRecorder.setProfile(camcorderProfile_HQ);
mRecorder.setOutputFile("/sdcard/MY_VIDEO.mp4");
}
private void Prepare()
{
try
{
mRecorder.setPreviewDisplay(mHolder.getSurface());
mRecorder.prepare();
}
catch (IllegalStateException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void UI_StartPreview()
{
if(mState == STATE_STOPPED || mState == STATE_NONE)
{
mRecorder= new MediaRecorder();
Init();
mCameraView= new SurfaceView(mContext);
mParent.addView(mCameraView);
this.mHolder = mCameraView.getHolder();
this.mHolder.addCallback(this);
this.mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
}
public void UI_StopPreview()
{
if(mState == STATE_PREVIEW)
{
if(mRecording)
{
UI_StopRecord();
}
if(mRecorder != null)
{
mRecorder.release();
mRecorder= null;
}
mParent.removeView(mCameraView);
//mCameraView= null;
}
}
public boolean UI_StartRecord()
{
if(mState != STATE_PREVIEW )
{
return false;
}
String path= "/sdcard/PLUS_VIDEO.mp4";
String state = android.os.Environment.getExternalStorageState();
if(!state.equals(Environment.MEDIA_MOUNTED))
{
return false;
}
File directory = new File(path).getParentFile();
if(!directory.exists() && !directory.mkdirs())
{
return false;
}
mRecorder.start();
mRecording= true;
mState= STATE_RECORDING;
return true;
}
public void UI_StopRecord()
{
if(mRecorder != null)
{
mRecorder.stop();
mRecorder.reset();
Init();
Prepare();
mRecording= false;
mState= STATE_PREVIEW;
}
}
public boolean UI_IsRecording()
{
return mRecording;
}
#Override
public void onInfo(MediaRecorder mr, int what, int extra)
{
// TODO Auto-generated method stub
Log.i(null, "onInfo");
}
#Override
public void surfaceCreated(SurfaceHolder holder)
{
Prepare();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
mState= STATE_PREVIEW;
}
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
mState= STATE_STOPPED;
}
}