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)
Related
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
I am making a camera app. I followed This tutorial to capture and save images in device. By implementing this, the image is captured and saved in device's gallery. It saves the image as file. But I want to get the bitmap of captured image. Here is my implementation,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_layout);
cameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
filepath = Environment.getExternalStorageDirectory();
if (checkCameraHardware(this)) {
// Create an instance of Camera
mCamera = getCameraInstance();
try {
// Get Camera Parameters
Camera.Parameters params = mCamera.getParameters();
// Set the Focus Mode
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
mCamera.setParameters(params);
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.cameraPreview);
preview.addView(mPreview);
} catch (Exception e) {
}
}
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
}
#Override
protected void onPause() {
// TODO OnPause Method
super.onPause();
releaseCamera();
}
// TODO Detecting Camera Hardware
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// This device has camera
return true;
} else {
// No Camera on this Device
return false;
}
}
// TODO Accessing Camera
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open();
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Takes the picture and write to file
File dir = new File(filepath.getAbsolutePath() + "/QR Codes/");
dir.mkdirs();
File pictureFile = getOutputMediaFile(FileColumns.MEDIA_TYPE_IMAGE);
if (pictureFile == null) {
Log.d("PICFILE",
"Error creating media file, check storage permissions");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
updateGallery();
} catch (Exception e) {
}
}
};
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
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;
}
Convert your image from file to Bitmap. Like,
Bitmap bmp = BitmapFactory.decodeFile(urImageFilePath);
Try:
Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data.length);
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(....;
I am working on a custom Camera activity for my application.
I was following the instruction from the Android Developers site here:
http://developer.android.com/guide/topics/media/camera.html
Everything seems to works fine, except the Callback function is not called and the picture is not saved. Here is my code:
public class CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
private static final String TAG = "CameraActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
// 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);
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "will now take picture");
mCamera.takePicture(null, null, mPicture);
Log.v(TAG, "will now release camera");
mCamera.release();
Log.v(TAG, "will now call finish()");
finish();
}
});
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.v(TAG, "Getting output media file");
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.v(TAG, "Error creating output file");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.v(TAG, e.getMessage());
} catch (IOException e) {
Log.v(TAG, e.getMessage());
}
}
};
private static File getOutputMediaFile() {
String state = Environment.getExternalStorageState();
if (!state.equals(Environment.MEDIA_MOUNTED)) {
return null;
}
else {
File folder_gui = new File(Environment.getExternalStorageDirectory() + File.separator + "GUI");
if (!folder_gui.exists()) {
Log.v(TAG, "Creating folder: " + folder_gui.getAbsolutePath());
folder_gui.mkdirs();
}
File outFile = new File(folder_gui, "temp.jpg");
Log.v(TAG, "Returnng file: " + outFile.getAbsolutePath());
return outFile;
}
}
After clicking the Button, I get logs: "will now take picture", "will now release camera" and "will now call finish". The activity finishes succesfully, but the Callback function was not called during the
mCamera.takePicture(null, null, mPicture);
function (There were no logs from the mPicture callback or getMediaOutputFile functions) and there is no file in the location that was specified.
Any ideas? :)
Much thanks!
The call to mCamera.takePicture() is asynchronous. That means that the call completes immediately, but the actual picture taking and processing happens sometime later. However, you do this immediately upon return from the call to mCamera.takePicture():
Log.v(TAG, "will now release camera");
mCamera.release();
Log.v(TAG, "will now call finish()");
finish();
That means that you have released the camera resources and finished the Activity before the camera gets a chance to actually take the picture and call you back.
You need to move that code into the callback method onPictureTaken() so that you release the resources and finish the Activity after the callback occurs.
Do it like this for taking multiple images on single Click Using SurfaceView Custom Camera
clickbtn.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
for (int i = 0; i < 5; i++) {
mcamera = mPreview.getCamera();
getimage(mcamera);
Toast.makeText(getApplicationContext(),
"multiple image count=" + i, 1000).show();
}
if (mPreview == null) {
mPreview = new CamLayer(MainActivity.this);
}
}
});
and
public static void getimage(Camera mcamera) {
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
pictureFile = getOutputMediaFile();
Log.e("path file 11111111", ""+pictureFile);
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (Exception e) {
}
}
};
try {
mcamera.startPreview();
mcamera.takePicture(null, null, mPicture);
Thread.sleep(2000);
} catch (Exception exception) {
exception.printStackTrace();
}
}
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"Sunil3");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
File mediaFile = new File(String.format(mediaStorageDir+File.separator+"%d.jpg", System.currentTimeMillis()));
return mediaFile;
}
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" />