I am creating an Android app and need a feature that takes photos without user interaction.
I simply want a class, for example, 'CameraService.java' that has a constructor that takes camera settings (eg. quality, res, etc) and a public function called 'takePhoto' which returns the image via type bitmap. I have been searching for a while to find out how I can do this using the Camera API 2 but have failed every time.
Most of the exemplars for doing this requires the camera to be made inside the MainActivity or in a class that extends Activity (I want to try to avoid this).
CameraService.java
I have utilized the following code found in a StackOverflow post (referenced below) which only saves the image to a hardcoded location (and uses Camera API 1) but I am experiencing errors.
package me.sam.camtest;
import android.hardware.Camera;
import android.util.Log;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class CameraService {
Camera mCamera;
private int quality;
public CameraService(int quality){
this.quality = quality;
}
private int findBackFacingCamera() {
int cameraId = -1;
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
break;
}
}
return cameraId;
}
private boolean safeCameraOpen(int id) {
boolean qOpened = false;
try {
releaseCamera();
mCamera = Camera.open(id);
qOpened = (mCamera != null);
} catch (Exception e) {
e.printStackTrace();
}
return qOpened;
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
Camera.PictureCallback mCall = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream("/sdcard/Image.jpg");
outStream.write(data);
outStream.close();
} catch (FileNotFoundException e){
Log.d("CAMERA", e.getMessage());
} catch (IOException e){
Log.d("CAMERA", e.getMessage());
}
}
};
public void takePhoto(){
// Should return bitmap in future
int back_cam = findBackFacingCamera();
if(back_cam != -1){
safeCameraOpen(1);
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
}
}
}
Runtime Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: me.sam.camtest, PID: 985
java.lang.RuntimeException: Unable to start activity ComponentInfo{me.sam.camtest/me.sam.camtest.MainActivity}: java.lang.RuntimeException: takePicture failed
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.RuntimeException: takePicture failed
at android.hardware.Camera.native_takePicture(Native Method)
at android.hardware.Camera.takePicture(Camera.java:1588)
at android.hardware.Camera.takePicture(Camera.java:1530)
at me.sam.camtest.CameraService.takePhoto(CameraService.java:74)
at me.sam.camtest.Reply.<init>(Reply.java:47)
at me.sam.camtest.MainActivity.onCreate(MainActivity.java:80)
at android.app.Activity.performCreate(Activity.java:6999)
at android.app.Activity.performCreate(Activity.java:6990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I researched this error and it seemed that people could only fix it by adding a Surface View which required the CameraService to be an activity or passed a context (not what I want).
In conclusion, How could I achieve the following:
Have a simple camera class that has one public method, "takePhoto" which
returns a bitmap
Avoid extending Activity or passing contexts in the simple camera class
Take the photo without user interaction (eg: intents)
PS: I am very new to the StackOverFlow community, I have tried to follow the guidelines with my best ability, please don't hate too much :)
My research:
https://androidmyway.wordpress.com/2012/09/07/capture-image/
How to take pictures in android application without the user Interface..?
http://www.41post.com/3794/programming/android-take-a-picture-without-displaying-a-preview
Related
I use Camera2 API for capturing OCR image in my App (Tablet only). Everything is work but there are one device (let say A Device) did'nt work. Here the log :
2021-05-28 13:46:23.402 28882-28937/com. D/OpenGLRenderer: textureCacheSize 75497472
2021-05-28 13:46:23.416 28882-28882/com. I/CameraManagerGlobal: Connecting to camera service
2021-05-28 13:46:33.303 28882-28975/com. W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'android.media.Image$Plane[] android.media.Image.getPlanes()' on a null object reference
2021-05-28 13:46:33.305 28882-28975/com. W/System.err: at com.Camera2Fragment$6$1.run(Camera2Fragment.java:927)
2021-05-28 13:46:33.307 28882-28975/com. W/System.err: at android.os.Handler.handleCallback(Handler.java:873)
2021-05-28 13:46:33.308 28882-28975/com. W/System.err: at android.os.Handler.dispatchMessage(Handler.java:99)
2021-05-28 13:46:33.310 28882-28975/com. W/System.err: at android.os.Looper.loop(Looper.java:193)
2021-05-28 13:46:33.311 28882-28975/com. W/System.err: at android.os.HandlerThread.run(HandlerThread.java:65)
Here my CaptureSession.CaptureCallback :
CameraCaptureSession.CaptureCallback CaptureCallback = new CameraCaptureSession.CaptureCallback() {
#Override
public void onCaptureCompleted(#NonNull CameraCaptureSession session, #NonNull CaptureRequest request, #NonNull TotalCaptureResult result) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Bitmap bitmap = null;
String nik;
try {
System.out.println("Array plane : " + mImageReader.acquireLatestImage().getPlanes().toString());
ByteBuffer buffer = mImageReader.acquireLatestImage().getPlanes()[0].getBuffer(); // Error start from here, in other device, acquireLatestImage is not null, but in A device is become null
byte[] data = new byte[buffer.remaining()];
buffer.get(data);
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (NullPointerException e) {
// **In one device, its fall to here**
e.printStackTrace();
}
if (bitmap == null) {
Toast.makeText(getActivity(), "Failed to get image, please try again", Toast.LENGTH_SHORT).show();
} else {
// other my code (proccessing image, ocr and other)
}
}
}
}
}
Extra :
The A device have screen specification 10 inch and 800x1280 and 8MP. I dont know its take a effect for the surface but its only happen in this device.
I have read some issues about getting an image from Camera2 API, but actually my code work on many many devices.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I tried to build an app that lets you send data over bluetooth to an
arduino. But I got stuck while creating the socket. The app keeps
crashing on startup, but I don't know why.
package de.lutherschule.bled.bluetoothled;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.icu.util.Output;
import android.support.annotation.WorkerThread;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
BluetoothAdapter bAdapter;
BluetoothDevice device;
Boolean found;
BluetoothSocket btSocket;
OutputStream outputStream;
InputStream inputStream;
public static final String DEVICE_ADRESS = "";
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final String TAG = "MainActvity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bAdapter = BluetoothAdapter.getDefaultAdapter();
found = false;
btSocket = null;
Log.v(TAG, "Funst");
if (bAdapter == null) {
Toast.makeText(getApplicationContext(),"Funst net",Toast.LENGTH_SHORT).show();
}
if(!bAdapter.isEnabled()) {
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
}
Set<BluetoothDevice> bondedDevices = bAdapter.getBondedDevices();
if(bondedDevices.isEmpty()) {
Toast.makeText(getApplicationContext(),"Muss gepaired werden",Toast.LENGTH_SHORT).show();
} else {
for (BluetoothDevice iter : bondedDevices) {
if(iter.getAddress().equals(DEVICE_ADRESS)) { // oder iter.getName() wenn Name bekannt muessen dann aendern
device=iter;
found=true;
break;
}
}
}
When I delete the section under this quote. The app starts just fine.
try{
btSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
}catch(IOException ioe){
Log.v(TAG, "socket nit erstellt");
}
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
device = bAdapter.getRemoteDevice(DEVICE_ADRESS);
try {
btSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket nit erstellt", Toast.LENGTH_LONG).show();
}
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
}
}
}
#Override
public void onPause() {
super.onPause();
try {
btSocket.close();
} catch (IOException e2) {
}
}
}
I'd appreciate any help. By the way sorry for my formatting... I'm a newbie in creating posts.
Android Monitor:
08-27 17:56:51.857 3071-3071/? E/libprocessgroup: failed to make and chown /acct/uid_10058: Read-only file system
08-27 17:56:51.857 3071-3071/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
08-27 17:56:51.857 3071-3071/? I/art: Not late-enabling -Xcheck:jni (already on)
08-27 17:56:52.086 3071-3071/de.lutherschule.bled.bluetoothled I/InstantRun: Starting Instant Run Server for de.lutherschule.bled.bluetoothled
08-27 17:56:52.288 3071-3071/de.lutherschule.bled.bluetoothled W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
[ 08-27 17:56:52.386 1162: 2146 D/ ]
HostConnection::get() New Host Connection established 0xb68aea60, tid 2146
08-27 17:56:52.429 3071-3079/de.lutherschule.bled.bluetoothled W/art: Suspending all threads took: 17.085ms
08-27 17:56:52.442 3071-3071/de.lutherschule.bled.bluetoothled E/BluetoothAdapter: Bluetooth binder is null
08-27 17:56:52.442 3071-3071/de.lutherschule.bled.bluetoothled V/MainActvity: Funst
08-27 17:56:52.452 3071-3071/de.lutherschule.bled.bluetoothled D/AndroidRuntime: Shutting down VM
--------- beginning of crash
08-27 17:56:52.453 3071-3071/de.lutherschule.bled.bluetoothled E/AndroidRuntime: FATAL EXCEPTION: main
Process: de.lutherschule.bled.bluetoothled, PID: 3071
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.lutherschule.bled.bluetoothled/de.lutherschule.bled.bluetoothled.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
at de.lutherschule.bled.bluetoothled.MainActivity.onCreate(MainActivity.java:59)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Try to use
BluetoothDevice device = mAdapter.getRemoteDevice(address);
btsocket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
Here is my code.
try {
socket = connect_device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
h.sendEmptyMessage(0);
} catch (IOException e) {
// TODO Auto-generated catch block
h.sendEmptyMessage(1);
e.printStackTrace();
try {
socket.close();
} catch (IOException e2) {
}
}
I have implemented an android camera with the help of official developer.android.com tutorial. The app is working fine sometimes but about 3/5 of times the preview of the camera freezes after some rotation and clicking the buttons or even without these works (other elements don't freeze). The cutest part is that when I debug the application the preview doesn't stuck but when I want to run the app normally sometimes the problem happens.
Here is my fullScreen Class which is consist of the codes that android studio generated for fullScreen activity and the codes for implementing surfaceHolder.Callback and camera stuff.
public class CameraActivity extends Activity implements SurfaceHolder.Callback {
... // some constants here
private Camera mCamera;
private SurfaceHolder mHolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
SurfaceView cameraSufaceView = (SurfaceView) findViewById(R.id.camera_preview);
// Accessing front camera to take picture
mCamera = openFrontFacingCameraGingerbread();
if (mCamera != null) {
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = cameraSufaceView.getHolder();
mHolder.addCallback(this);
} else {
// Alter user
}
/**
* Gets an instance of front facing camera if available
*/
#SuppressWarnings("deprecation")
private Camera openFrontFacingCameraGingerbread() {
int cameraCount;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
cam = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return cam;
}
#Override
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());
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// 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
}
// start preview with new settings
try {
// mCamera.setDisplayOrientation(needs degree here);
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e) {
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
releaseCamera();
}
#Override
protected void onPause() {
super.onPause();
releaseCamera();
}
#Override
protected void onResume() {
super.onResume();
if (mCamera == null)
mCamera = openFrontFacingCameraGingerbread();
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
When this problem happens some errors appear in the LogCat but they are not really informative. here are they:
26893-26893/com.naviiid.retinaflash E/art﹕ No implementation found for void java.lang.Runtime.appStartupEnd() (tried Java_java_lang_Runtime_appStartupEnd and Java_java_lang_Runtime_appStartupEnd__)
09-16 01:34:09.336 26893-26893/com.naviiid.retinaflash E/ActivityThread﹕ appStartupEnd :
java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at android.app.ActivityThread.appStartupEnd(ActivityThread.java:305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2819)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
Caused by: java.lang.UnsatisfiedLinkError: No implementation found for void java.lang.Runtime.appStartupEnd() (tried Java_java_lang_Runtime_appStartupEnd and Java_java_lang_Runtime_appStartupEnd__)
at java.lang.Runtime.appStartupEnd(Native Method)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at android.app.ActivityThread.appStartupEnd(ActivityThread.java:305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2819)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
The only clue that I have found so far is that sometimes android calls onPause method even if the activity isn't paused. For getting instance of the camera again I call openFrontFacingCameraGingerbread() in onResume method.
im trying to run a Camera Service in the Background, as soon after the Service has started i get an error takePicture failed. I'm new to Android,new to Stackoverflow and also not a good programmer.
I've added the right permissions and the service has been declared in the manifest file too.
package com.example.nevii.camera;
import android.app.Service;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.IBinder;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
import java.io.IOException;
public class CameraService extends Service
{
//Camera variables
//a surface holder
private SurfaceHolder sHolder;
//a variable to control the camera
private Camera mCamera;
//the camera parameters
private Parameters parameters;
private boolean safeToTakePicture = false;
/** Called when the activity is first created. */
#Override
public void onCreate()
{
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
super.onStartCommand(intent, flags, startId);
Toast.makeText(getBaseContext(), "onStartCommand", Toast.LENGTH_SHORT).show();
mCamera = Camera.open(1);
mCamera.setDisplayOrientation(90);
SurfaceView sv = new SurfaceView(getApplicationContext());
try {
mCamera.setPreviewDisplay(sv.getHolder());
parameters = mCamera.getParameters();
//set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
safeToTakePicture = true;
takePic();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//stop the preview
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
//release the camera
mCamera.release();
//unbind the camera from this object
mCamera = null;
}
//Get a surface
sHolder = sv.getHolder();
//tells Android that this surface will have its data constantly replaced
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
return START_STICKY;
}
public void takePic(){
Camera.PictureCallback mCall = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
//decode the data obtained by the camera into a Bitmap
MyCamera myCamera = new MyCamera();
myCamera.SavePicture(data);
//stop the preview
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
//release the camera
mCamera.release();
//unbind the camera from this object
mCamera = null;
}
};
mCamera.takePicture(null, null, mCall);
Toast.makeText(getApplicationContext(),"Pic taken",Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
I got the SourceCode from here:http://androideasylessons.blogspot.ch/2012/09/capture-image-without-surface-view-as.html
In the MainActivity i started the Service using:
startService(new Intent(this, CameraService.class));
myCamera.SavePicture is just an Asynchtask, which saves the Picture, i don't think there's a problem with that.
I hope you guys can help me.
Happy Coding!
UPDATE Logcat Error:
03-03 09:04:46.150 27530-27530/com.example.nevii.videocam D/Camera﹕ app passed NULL surface
03-03 09:04:46.153 27530-27530/com.example.nevii.videocam D/AndroidRuntime﹕ Shutting down VM
03-03 09:04:46.154 27530-27530/com.example.nevii.videocam E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.nevii.videocam, PID: 27530
java.lang.RuntimeException: Unable to start service com.example.nevii.videocam.CameraService#3f53f37f with Intent { cmp=com.example.nevii.videocam/.CameraService }: java.lang.RuntimeException: takePicture failed
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2881)
at android.app.ActivityThread.access$2100(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1376)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.RuntimeException: takePicture failed
at android.hardware.Camera.native_takePicture(Native Method)
at android.hardware.Camera.takePicture(Camera.java:1436)
at android.hardware.Camera.takePicture(Camera.java:1381)
at com.example.nevii.videocam.CameraService.takePic(CameraService.java:101)
at com.example.nevii.videocam.CameraService.onStartCommand(CameraService.java:57)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2864)
at android.app.ActivityThread.access$2100(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1376)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
just add SurfaceTexture st = new SurfaceTexture(MODE_PRIVATE); mCamera.setPreviewTexture(st);
before mCamera.startPreview();
I have a torch class, when I use ledon() my flashlight turns on.
When I use ledoff() it turns off. But if i try to turn it back on again, I get a force close.
And then it turns on again if I try.
What is the reason for the force close?
import android.hardware.Camera;
import android.util.Log;
import static android.hardware.Camera.*;
/**
* Created by tyler on 8/13/13.
*/
public class Torch {
private static final String TAG = "Light";
private static Camera mCamera;
private static Camera.Parameters mParameters;
public static Camera getCameraInstance() {
Camera c = null;
try {
c = open();
} catch (Exception e) {
}
return c;
}
public static void ledon()
{
mCamera = getCameraInstance();
mParameters = mCamera.getParameters();
mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(mParameters);
Log.d(TAG, "Turn On");
}
public static void ledoff(MainActivity activity) {
String flashMode = mParameters.getFlashMode();
if (Camera.Parameters.FLASH_MODE_OFF.equals(flashMode)) {
mCamera = getCameraInstance();
}
mParameters = mCamera.getParameters();
mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
mCamera.setParameters(mParameters);
Log.d(TAG, "Turn Off");
}
}
EDIT: Here is my updated code, it turns off and on all I want, but when I turn it on and then on again, it Force Closes. Logcat below code.
import android.hardware.Camera;
import android.util.Log;
/**
* Created by tyler on 8/13/13.
*/
public class Torch {
private static final String TAG = "Light";
private static Camera mCamera;
private static Camera.Parameters mParameters;
public static Camera getCameraInstance() {
Camera c = null;
try {
c = mCamera.open();
} catch (Exception e) {
}
return c;
}
public static void ledon() {
mCamera = getCameraInstance();
mParameters = mCamera.getParameters();
String flashMode = mParameters.getFlashMode();
if (! flashMode.equals(Camera.Parameters.FLASH_MODE_TORCH)) {
mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(mParameters);
Log.d(TAG, "Turn On");
}
}
public static void ledoff() {
String flashMode = mParameters.getFlashMode();
if (! flashMode.equals(Camera.Parameters.FLASH_MODE_OFF)) {
mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
mCamera.setParameters(mParameters);
mCamera.release();
Log.d(TAG, "Turn Off");
}
}
}
Logcat:
08-15 12:01:10.502 25951-25951/com.tyler.myapp W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x4170f898)
08-15 12:01:10.522 25951-25951/com.tyler.myapp E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.tyler.myapp.Torch.ledon(Torch.java:28)
Without your logcat, nobody can say for sure what is your problem, but I suspect something. After calling ledon you should call mCamera.release() to tell the android system that you are no longer using the Camera. If you don't call this, on the next call to ledon, you try to allocate a new Camera object, but the Camera with id=0 is used by an application, which is YOUR application, and therefore it throws a RuntimeException. You catch it, and then set the mCamera to null and then later reference mCamera, hence the NullPointerException which I suspect to be the cause.
I'm not sure as I didn't check it but I think because you are updating the mParameters in the ledOff.
try this method
public static void ledSwitch() {
mCamera = getCameraInstance();
mParameters = mCamera.getParameters();
String flashMode = mParameters.getFlashMode();
if (Camera.Parameters.FLASH_MODE_OFF.equals(flashMode)) {
mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
Log.d(TAG, "Turn On");
} else {
mCamera.release()
mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
Log.d(TAG, "Turn Off");
}
}
this method will check if it's on will make it off, if it's off will make it on.
I took .release() from Levente Kurusa :D
updated --
try this, as an HTC user I use different way of camera as I read, so I searched the internet for you.
public static Camera mCameraDevice;
private static List<String> flashModes;
private static String currentFlashMode;
Camera.Parameters param = mCameraDevice.getParameters();
flashModes = param.getSupportedFlashModes();
if (flashModes != null) {
currentFlashMode = param.getFlashMode();
if (currentFlashMode.equals(Parameters.FLASH_MODE_OFF)) {
currentFlashMode = Parameters.FLASH_MODE_ON;
}
else {
currentFlashMode = Parameters.FLASH_MODE_OFF;
}
param.setFlashMode(currentFlashMode);
mCameraDevice.setParameters(param);
}
&& don't forget to use these permissions
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />