I can't open the Google Glass Camera - android

I've got this code (based on http://developer.android.com/training/camera/cameradirect.html), but on Google Glass not works for me.
The code:
public class MainActivity extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
private GestureDetector mGestureDetector;
private Camera.PictureCallback mPicture;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGestureDetector = createGestureDetector(this);
mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
// Log.d("Camera", "Error creating media file, check storage permissions: " + e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("Camera", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("Camera", "Error accessing file: " + e.getMessage());
}
}
};
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
}
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
This line returns nullPointerException:
preview.addView(mPreview);
The getCameraInstance method:
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
System.out.println(e.getMessage());
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
I pretend to take a photo without a "TAP" gesture... is there any suggestion?
I have read other posts, but I have not found any solution yet :(
Thanks in advance!
UPDATED
The null Pointer have been solved, but now, the application returns me this error: "Fail to connect to camera service"

Issue:
Since you are using the Android camera APIs(http://developer.android.com/training/camera/cameradirect.html) versus Google Glasses specific Camera APIs(https://developers.google.com/glass/develop/gdk/camera), you will most likely need to restart your Google Glass.
See other SO question: java.lang.RuntimeException: Fail to Connect to camera service
I have ran into this issue many times. Basically, when you are attempting to connect the Camera and you did not close out the Camera service properly, you will not be able to connect back to it again. I ran into this using the Android APIs and OpenCV's APIs.
Please follow the example below after restarting your device.
Example:
MainActivity:
public class MainActivity extends Activity {
private CameraSurfaceView cameraView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initiate CameraView
cameraView = new CameraSurfaceView(this);
// Set the view
this.setContentView(cameraView);
}
#Override
protected void onResume() {
super.onResume();
// Do not hold the camera during onResume
if (cameraView != null) {
cameraView.releaseCamera();
}
}
#Override
protected void onPause() {
super.onPause();
// Do not hold the camera during onPause
if (cameraView != null) {
cameraView.releaseCamera();
}
}
}
CameraSurfaceView:
public class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
private Camera camera;
#SuppressWarnings("deprecation")
public CameraSurfaceView(Context context) {
super(context);
final SurfaceHolder surfaceHolder = this.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
// Show the Camera display
try {
camera.setPreviewDisplay(holder);
} catch (IOException e) {
this.releaseCamera();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// Start the preview for surfaceChanged
if (camera != null) {
camera.startPreview();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// Do not hold the camera during surfaceDestroyed - view should be gone
this.releaseCamera();
}
/**
* Release the camera from use
*/
public void releaseCamera() {
if (camera != null) {
camera.release();
camera = null;
}
}
}
References:
I know this because I worked on a big Google Glass repository of examples located here: https://github.com/jaredsburrows/OpenQuartz.
Please see my personal Camera example here: https://github.com/jaredsburrows/OpenQuartz/tree/master/examples/CameraPreview.
Other SO question: java.lang.RuntimeException: Fail to Connect to camera service

Related

How send mms or sms capture photo automatically in android phone? 0

I have created my own camera application. And when I click the button it takes the picture and saves it in the galary. What I want to do is to take the picture send automatic sms or mms. Please help me how can it. My code here:
public class SimpleCameraIntentFragment extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
public static final int MEDIA_TYPE_IMAGE = 1;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=(ImageView)findViewById(R.id.imageView1);
Button captureButton = (Button) findViewById(R.id.button_capture);
System.out.println("Starting!");
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
final PictureCallback mPicture = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
MediaStore.Images.Media.insertImage(getContentResolver(),
pictureFile.getAbsolutePath(),
pictureFile.getName(), pictureFile.getName());
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
captureButton.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
// get an image from the camera
final Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
mCamera.takePicture(null, null, mPicture);
t.cancel();
//imageView.set
}
}, 5000);
}
});
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
#Override
protected void onPause() {
super.onPause();
releaseCamera(); // release the camera immediately on pause event
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
/** Create a File for saving an image or video */
private File getOutputMediaFile(int type) {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
}
You can see some tutorial here : http://www.mkyong.com/android/how-to-send-sms-message-in-android/.
But I don't think the user appreciate a app who send automatically SMS or MMS.
The code look's like that :
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendDataMessage(....;

OnPictureTaken() Timing/Saving Issue

I'm creating a custom camera application (which'll be contained within a larger, main application) that loads up a view with the camera -preview and a picture gallery preview - so the user can either take a picture or select a preexisting one. If the user does take a photo, I just wanna display a confirmation dialog and, if confirmed, pass control back to the main activity. I can't store the photo: need to quickly use it as an attachment, and once sent via the main activity, dispose of it.
The problem comes up when I take a picture and onPictureTaken() is called: it either doesn't work, or takes an absurdly long time for it to save a photo. Also, I can't seem to figure out how to extract the photo right on the spot, without saving it to a directory; I planned on immediately deleting the directory, but there's got to be a cleaner way (essentially, I just wanna access that raw byte array, without having to save it).
I want it to be modular (gonna use the camera a lot in my upcoming projects), and I think that's what's adding to the overall lag.
I followed Google's Developer Android Guide on Cameras, and most of my code is derived from the examples presented there.
I'm also using ActionBarSherlock.
I currently have three classes:
CameraManager
public class CameraManager {
private static Camera CAMERA;
/** Check if this device has a camera */
public static boolean doesDeviceHaveCamera(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
return true;
}
else {
return false;
}
}
public static Camera getCameraInstance(){
CAMERA = null;
try {
CAMERA = Camera.open();
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return CAMERA;
}
}
CameraPreview
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "CameraPreview";
private SurfaceHolder surfaceHolder;
private Camera camera;
public CameraPreview(Context context, Camera camera) {
super(context);
this.camera = camera;
surfaceHolder = getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); // deprecated setting, but required on Android versions prior to 3.0
}
public void surfaceCreated(SurfaceHolder holder) {
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
}
catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
}
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 (surfaceHolder.getSurface() == null){
return;
}
try {
camera.stopPreview();
}
catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
camera.setDisplayOrientation(90);
// start preview with new settings
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}
catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
}
CameraActivity
public class CameraActivity extends SherlockActivity {
private static final String TAG = "CameraActivity";
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Camera camera;
private CameraPreview preview;
private PictureCallback picture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions: media file is null.");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
}
catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
}
catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.camera_view);
/**Get a camera instance**/
if(CameraManager.doesDeviceHaveCamera(this)){
camera = CameraManager.getCameraInstance();
}
else{
return;
}
/**Create a SurfaceView preview (holds the camera feed) and set it to the corresponding XML layout**/
preview = new CameraPreview(this, camera);
FrameLayout previewContainer = (FrameLayout) findViewById(R.id.camera_preview);
previewContainer.addView(preview);
/**Set up a capture button, which takes the picture**/
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
camera.takePicture(null, null, picture);
}
});
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyDirectory");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyDirectory", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
}
else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
}
else {
return null;
}
return mediaFile;
}
}
I'm calling CameraActivity from a button on my main activity screen.
The problem comes up when I take a picture and onPictureTaken() is called: it either doesn't work, or takes an absurdly long time for it to save a photo
It is a large file, one that you are writing to on the main application thread.
essentially, I just wanna access that raw byte array, without having to save it
Then don't save it. Carefully use a static data member to put the byte array somewhere that the main activity can use (and, when you are done with it, null out the static reference, so the memory can be garbage-collected).
If you open the camera on a secondary event thread, your pictureTaken() callback will be called on that thread, not hindering UI responsiveness. Note that you can still call camera.takePicture() from onClick(), i.e. from the UI thread.
This still is not a silver bullet: you may want to offload writing file to a yet another working thread, to let the camera take the next photo. And as Mark wrote above, don't write to file if you only need live access to the raw byte array.

App crashing while building custom Camera

Application is crashing on click of the button to capture image.Kindly help.Below is my code.I have used SurfaceView to preview.I guess there is some problem with Picture CallBack
public class MainActivity extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
public static final int MEDIA_TYPE_IMAGE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button captureButton = (Button) findViewById(R.id.button_capture);
System.out.println("Starting!");
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
final PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d("TAG", "Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("TAG", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("TAG", "Error accessing file: " + e.getMessage());
}
}
};
// Add a listener to the Capture button
captureButton.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
// get an image from the camera
System.out.println("Photo Taking!");
mCamera.takePicture(null, null, mPicture);
}
}
);
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
#Override
protected void onPause() {
super.onPause();
releaseCamera(); // release the camera immediately on pause event
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
/** Create a File for saving an image or video */
private File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
}
Logcar error:
java.lang.NullPointerException
com.example.demo.MainActivity$2.onClick(MainActivity.java:82)
android.view.View.performClick(View.java:4084)
android.view.View$PerformClick.run(View.java:16966)
android.os.Handler.handleCallback(Handler.java:615)
android.os.Handler.dispatchMessage(Handler.java:92)
android.os.Looper.loop(Looper.java:137)
android.app.ActivityThread.main(ActivityThread.java:4745)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:511)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
dalvik.system.NativeStart.main(Native Method)

Camera Preview on Android

I am trying to make a camera application on Android, no errors in Log-cat but the application doesn't close when i press the back button ; and if i want to open another application camera after stopping it; the camera is locked !! any hint or ideas ?
Thanks in advance.
public class Capture extends Activity {
private Camera mCamera;
private ViewCamera mPreview;
public static final int MEDIA_TYPE_IMAGE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
releaseCamera();
// Create an instance of Camera
mCamera = getCameraInstance();
Log.d("EyeSeeJD", "getCameraInstance");
// Create our Preview view and set it as the content of our activity.
mPreview = new ViewCamera(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.frame);
Log.d("EyeSeeJD", "addview ");
preview.addView(mPreview);
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
// c.lock();
} catch (Exception e) {
// Camera is not available (in use or does not exist)
Log.d("EyeSeeJD", "can't open camera ");
}
return c; // returns null if camera is unavailable
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type) {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null) {
Log.d("EyeSeeJD",
"Error creating media file, check storage permissions ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("EyeSeeJD", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("EyeSeeJD", "Error accessing file: " + e.getMessage());
}
}
};
#Override
protected void onResume() {
super.onResume();
/*
* if (mCamera == null) { releaseCamera(); // release the camera
* immediately on pause event System.exit(0); }
*/
}
#Override
protected void onPause() {
super.onPause();
releaseCamera(); // release the camera immediately on pause event
// System.exit(0);
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mPreview.getHolder().removeCallback(mPreview);
// mCamera.unlock();
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
#Override
public void onBackPressed() { // TODO Auto-generated methodstub
super.onBackPressed();
//mCamera.setPreviewCallback(null);
//mPreview.getHolder().removeCallback(mPreview);
mCamera.stopPreview();
mCamera.release(); // release the camera for other applications
mCamera = null;
finish();
System.exit(0);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
//mCamera.setPreviewCallback(null);
mCamera.takePicture(null, null, mPicture);
//mCamera.release();
// mCamera.startPreview();
return super.onTouchEvent(event);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mPreview.getHolder().removeCallback(mPreview);
mCamera.release(); // release the camera for other applications
mCamera = null;
finish();
System.exit(0);
}
}
ViewCamera.java
public class ViewCamera extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder = null;
private Camera mCamera = null;
public ViewCamera(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
// The Surface has been created, now tell the camera where to draw the
// preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("EyeSeeJD", "Error setting camera preview: " + e.getMessage());
}
}
// check if device has camera
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
Log.d("EyeSeeJd", "there is a camera ");
return true;
} else {
// no camera on this device
Log.d("EyeSeeJd", "there is no camera ");
return false;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// TODO Auto-generated method stub
// 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
/*Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(320, 480);
mCamera.setParameters(parameters);*/
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
// mCamera.unlock();
} catch (Exception e) {
Log.d("EyeSeeJd",
"Error starting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
// empty. Take care of releasing the Camera preview in your activity.
this.getHolder().removeCallback(this);
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
It's hard to tell what really happens without following your code in debugger, but there is a chance that you call Camera.release() too many times. There may be NullPointerExeception somewhere that prevents normal shutdown. There should be only one release in your app, and onPause() is a perfect place to call releaseCamera(). I don't see why you need to override onBackPressed() at all, calling finish() from this override is not recommended, and calling System.exit() even more so. Also, I would move call to getCameraInstance() to onResume() or maybe to onStart().
The reason why your app takes time to close when you press back is that your app is crashing because in onBackPressed() method you are setting mCamera to null and in onDestroy() you are using it again to stop and releasing camera.

Open default camera on SurfaceView and record with front camera

I have write this code to open the front camera on surfaceview in the screen, but when you click on the button i want to record a video with front camera.
This code crash. i have used two different variable for the cameras, but i don t find my error :(.. I have followed the google guide.
public class MainActivity extends Activity {
public static final int MEDIA_TYPE_VIDEO = 2;
private Camera mCamera;
private CameraPreview mPreview;
public static final int MEDIA_TYPE_IMAGE = 1;
protected static final String TAG = null;
private MediaRecorder mMediaRecorder;
private Camera mCamerafront;
private boolean isRecording = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Button captureButton = (Button) findViewById(id.button_capture);
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
if (isRecording) {
// stop recording and release camera
mMediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object
mCamerafront.lock(); // take camera access back from MediaRecorder
// inform the user that recording has stopped
//setCaptureButtonText("Capture");
isRecording = false;
} else {
// initialize video camera
if (prepareVideoRecorder()) {
// Camera is available and unlocked, MediaRecorder is prepared,
// now you can start recording
mMediaRecorder.start();
// inform the user that recording has started
//setCaptureButtonText("Stop");
isRecording = true;
} else {
// prepare didn't work, release the camera
releaseMediaRecorder();
// inform user
}
}
}
}
);
/* captureButton.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);*/
}
//*PARTE registrazione
private boolean prepareVideoRecorder(){
int cameraCount = Camera.getNumberOfCameras()-1;
mCamerafront=Camera.open(cameraCount);
mMediaRecorder = new MediaRecorder();
mCamerafront.unlock();
mMediaRecorder.setCamera(mCamerafront);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
Log.d(TAG, "IllegalStateException preparing MediaRecorder: " + e.getMessage());
// releaseMediaRecorder();
return false;
} catch (IOException e) {
Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
//releaseMediaRecorder();
return false;
}
return true;
}
private void releaseMediaRecorder(){
if (mMediaRecorder != null) {
mMediaRecorder.reset(); // clear recorder configuration
mMediaRecorder.release(); // release the recorder object
mMediaRecorder = null;
mCamerafront.lock(); // lock camera for later use
}
}
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private final String TAG = null;
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
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());
}
}
}
#Override
protected void onPause() {
super.onPause();
// if you are using MediaRecorder, release it first
releaseCamera(); // release the camera immediately on pause event
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
private PictureCallback mPicture = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
You need to add the following permission in yout AndroidManifest.xml file:
<uses-permission android:name="android.permission.RECORD_AUDIO" />

Categories

Resources