I got an exception while releasing camera object "java.lang.RuntimeException: Method called after release"
following is my code and exception stack trace.
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
Exception stack trace -
java.lang.RuntimeException: Method called after release()
Thread[main,5,main] android.hardware.Camera._stopPreview(Native Method)
android.hardware.Camera.stopPreview(Camera.java:626)
com.s5.selfiemonkey1.activity.Preview.surfaceDestroyed(Preview.java:152)
android.view.SurfaceView.updateWindow(SurfaceView.java:601)
android.view.SurfaceView.access$000(SurfaceView.java:88)
android.view.SurfaceView$3.onPreDraw(SurfaceView.java:183)
android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:680)
android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2123)
android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1139)
android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4872)
android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
android.view.Choreographer.doCallbacks(Choreographer.java:579)
android.view.Choreographer.doFrame(Choreographer.java:548)
android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
android.os.Handler.handleCallback(Handler.java:800)
android.os.Handler.dispatchMessage(Handler.java:100)
android.os.Looper.loop(Looper.java:194)
android.app.ActivityThread.main(ActivityThread.java:5371)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:525)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
it look like stopPreview() is called on released object.
I had made a method which would return me boolean depending of whether camera is in use or not. Below is a small snipet:
public static Camera checkForCamera(){
Camera camera = null;
try {
camera = Camera.open(); // this line will throw exception if camera is not in use.
}
catch (Exception e){
// if exception is thrown, return your boolean value here...
}
return camera; // if instance of camera, if it is not available it will return null.
}
Related
Hi friends I'm trying to make torch application in unity.From documentation I have noticed that setTorchMode() is applicable only if we have API>22. It works fine for API>22.But for below API<23 I have followed this. But even though my application in not staring torch in API<23 . From Logcat I have traced that CameraService: Permission Denial: can't use the camera
Detail Error Report:
08-18 09:27:22.343 758-835/? I/ActivityManager: Killing
14121:com.google.android.partnersetup/u0a7 (adj 15): DHA:empty #19
08-18 09:27:22.343 196-2615/? W/ServiceManager: Permission failure:
android.permission.CAMERA from uid=10242 pid=14010
08-18 09:27:22.343 196-2615/? E/CameraService: Permission Denial: can't
use the camera pid=14010, uid=10242
08-18 09:27:22.343 14010-14051/? W/CameraBase: An error occurred while
connecting to camera: 0
08-18 09:27:22.353 14010-14051/? E/ContentValues: TorchMode:
java.lang.RuntimeException: Fail to connect to camera service
`enter code here`at android.hardware.Camera.<init>(Camera.java:568)
at android.hardware.Camera.open(Camera.java:426)
at
com.mugames.torchlibrary.AndroidTrochClass.TorchMode
(AndroidTrochClass.java:64)
at com.unity3d.player.UnityPlayer.nativeRender(Native Method)
at com.unity3d.player.UnityPlayer.access$300(Unknown Source)
at com.unity3d.player.UnityPlayer$e$1.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:145)
at com.unity3d.player.UnityPlayer$e.run(Unknown Source)
Here is my C# (Unity Code)
private void Awake()
{
if(!Permission.HasUserAuthorizedPermission(Permission.Camera))
{
Permission.RequestUserPermission(Permission.Camera);
}
}
void Start()
{
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaObject context = activity.Call<AndroidJavaObject>("getApplicationContext");
javaObject = new AndroidJavaObject("com.mugames.torchlibrary.AndroidTrochClass");
javaObject.Call("Init", context);
javaObject.Call("TorchMode", true);
}
Also Here is my Java code(Name of JAVA class is AndroidTrochClass) for API<23
try {
if(camera== null && parameters==null) {
camera = Camera.open();
parameters = camera.getParameters();
List<String> modesAvailable = parameters.getSupportedFlashModes();
if (modesAvailable.contains(Camera.Parameters.FLASH_MODE_TORCH)) {
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
} else if (modesAvailable.contains((Camera.Parameters.FLASH_MODE_ON))) {
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_ON);
} else {
Log.d("Unity", "No Flash Available");
}
camera.setParameters(parameters);
}
if (state) {
camera.startPreview();
} else {
camera.stopPreview();
}
}
catch (Exception e)
{
Log.e(TAG, "TorchMode: ",e);
e.printStackTrace();
}
NOTE: I'm using Java Class Just as Plugin So Java Class extend to nothing so I have passed current context to Java Methods
Found!! I need to add Camera permission in manifest file ;)
I have tried the following code,
try {
final Activity activity = ctx;
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
android.app.Fragment prev = activity.getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
DialogServiceFailed newFragment = DialogServiceFailed.newInstance(pageName, onServiceFailed);
newFragment.show(ft, "dialog");
ft.addToBackStack(null);
ft.commitAllowingStateLoss();
} catch (ClassCastException e) {
Log.d("Log", "Can't get the fragment manager with this");
}
But I get the following exception and my app crashes.
java.lang.IllegalStateException: commit already called
at android.app.BackStackRecord.commitInternal(BackStackRecord.java:582)
at android.app.BackStackRecord.commitAllowingStateLoss(BackStackRecord.java:578)
at com.brightspot.extrain5psim.model.APIRequestHandler.loadServiceFailedDialog(APIRequestHandler.java:99)
at com.brightspot.extrain5psim.view.fragments.LoginFragment.setOnAsyncTaskCompleted(LoginFragment.java:201)
at com.brightspot.extrain5psim.model.APIRequestHandler.onPostExecute(APIRequestHandler.java:80)
at com.brightspot.extrain5psim.model.APIRequestHandler.onPostExecute(APIRequestHandler.java:17)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5317)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
newFragment.show(ft, "dialog")
show calls internally commit. So you probably want get rid of
ft.commitAllowingStateLoss();
or you can get rid of
newFragment.show(ft, "dialog");
add call
ft.add(newFragment, "dialog");
ft.commitAllowingStateLoss();
Edit
this is what DialogFragment's show() looks like
public int show(FragmentTransaction transaction, String tag) {
mDismissed = false;
mShownByMe = true;
transaction.add(this, tag);
mViewDestroyed = false;
mBackStackId = transaction.commit();
return mBackStackId;
}
i am trying to check for internet connection in my application.
first, i am checking if wifi or mobile data is on, then i am checking if there is an active internet connection.
what i am currently doing:
public class ConnectivityReceiver extends BroadcastReceiver {
String TAG="ConnectivityReceiver";
public static boolean hasInternetAccess() {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0);
} catch (IOException e) {
}
return false;
}
#Override
public void onReceive(Context arg0, Intent intent) {
String action = intent.getAction();
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,false);
if(noConnectivity){
try{
TaskListAndOptionsActivity.item3.setIcon(R.drawable.ic_action_network_nowifi);
}
catch(Exception e)
{
}
}
else
{
Boolean status = hasInternetAccess();
if(status==true)
{
try{
TaskListAndOptionsActivity.item3.setIcon(R.drawable.ic_action_network_wifi);
}
catch(Exception e)
{
}
}
else
{
try{
TaskListAndOptionsActivity.item3.setIcon(R.drawable.ic_action_network_nowifi);
}
catch(Exception e)
{
}
}
}
}
but i am getting the following error:
java.lang.RuntimeException: Unable to start receiver connectionchecker.ConnectivityReceiver: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2668)
at android.app.ActivityThread.access$1800(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5653)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1166)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:390)
at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:343)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:289)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
at connectionchecker.NetworkUtil.hasInternetAccess(NetworkUtil.java:21)
at connectionchecker.ConnectivityReceiver.onReceive(ConnectivityReceiver.java:46)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2653)
at android.app.ActivityThread.access$1800(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5653)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
You are trying to connect to the network in UI thread which is not allowed. to check for active internet connection use following method.
public boolean isConnected() {
ConnectivityManager manager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return true;
} else {
return false;
}
}
Once you receive the value, if it is true proceed with network operation. Else display the user a proper error message.
Caused by: android.os.NetworkOnMainThreadException
You need to perform network operation not on UIthread.
Sounds like you might need to use the getActiveNetworkInfo() call. There is a few posts on stackoverflow already that document it extensively so rather than repeat those have a look at these:
Detect whether there is an Internet connection available on Android
I am trying to implement the camera SDK example code from the Android website, but when I try to run the app I get this Null Pointer Exception and logcat doesn't really give me a whole lot of info to go on. I am pretty new to Android development so I am not sure how to proceed in debugging this issue.
06-07 09:48:24.960 927-927/com.luketim.cam.cam2.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.luketim.cam.cam2.app, PID: 927
java.lang.NullPointerException
at com.luketim.cam.cam2.app.CameraPreview.surfaceCreated(CameraPreview.java:34)
at android.view.SurfaceView.updateWindow(SurfaceView.java:572)
at android.view.SurfaceView.access$000(SurfaceView.java:86)
at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:175)
at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:847)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1871)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Here is the class with the method where this NullPointerException is thrown.
package com.luketim.cam.cam2.app;
import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
/**
* Created by luketimothy on 06/06/2014.
*/
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "";
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());
}
}
}
logcat doesn't really give me a whole lot of info to go on
It tells you the line of code on which you crashed (CameraPreview.java:34, in your surfaceCreated() method), and why you crashed (a NullPointerException occurred on that line).
Since there are only two lines in surfaceCreated(), it is clear that mCamera is null. Since that is provided from outside the code that you have listed, you will need to track down where you are opening the camera and determine why that did not work as expected.
FWIW, writing a camera application in Android is rather difficult. It is not something that somebody new to Android should be attempting. I offer a library to try to simplify using the camera from within an app, but even that does not yet handle every oddball thing that device manufacturers do.
I'm following the Camera guide on Android developers. However when I try to run the activity I get a Java lang NullPointer Exception which I don't understand where it's coming from.
This is the Camera activity I wrote down.
public class Call extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call);
// Create an instance of Camera
mCamera = getCameraInstance();
System.out.println(Camera.open());
// 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);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.start_call, menu);
return true;
}
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
System.out.println("Has a camera it has "+Camera.getNumberOfCameras());
getCameraInstance();
return true;
} else {
// no camera on this device
System.out.println("Does not have a camera");
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
System.out.println("Got the camera");
}
catch (Exception e){
// Camera is not available (in use or does not exist)
System.out.println("Not available");
}
return c; // returns null if camera is unavailable
}
}
and this is the camerapreview class
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
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("error", "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("error", "Error starting camera preview: " + e.getMessage());
}
}
}
This is the error I got.
07-24 17:55:11.856: E/AndroidRuntime(796): FATAL EXCEPTION: main
07-24 17:55:11.856: E/AndroidRuntime(796): java.lang.NullPointerException
07-24 17:55:11.856: E/AndroidRuntime(796): at com.reflap.reflap.CameraPreview.surfaceCreated(CameraPreview.java:31)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.SurfaceView.updateWindow(SurfaceView.java:543)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.SurfaceView.access$000(SurfaceView.java:81)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:169)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:671)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1820)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4214)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.Choreographer.doCallbacks(Choreographer.java:555)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.Choreographer.doFrame(Choreographer.java:525)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.os.Handler.handleCallback(Handler.java:615)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.os.Handler.dispatchMessage(Handler.java:92)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.os.Looper.loop(Looper.java:137)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.app.ActivityThread.main(ActivityThread.java:4745)
07-24 17:55:11.856: E/AndroidRuntime(796): at java.lang.reflect.Method.invokeNative(Native Method)
07-24 17:55:11.856: E/AndroidRuntime(796): at java.lang.reflect.Method.invoke(Method.java:511)
07-24 17:55:11.856: E/AndroidRuntime(796): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
07-24 17:55:11.856: E/AndroidRuntime(796): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
07-24 17:55:11.856: E/AndroidRuntime(796): at dalvik.system.NativeStart.main(Native Method)
07-24 17:55:15.045: I/Process(796): Sending signal. PID: 796 SIG: 9
07-24 17:55:15.956: E/Trace(817): error opening trace file: No such file or directory (2)
I don't know where the null is coming from. I did print out this System.out.println(Camera.open()); and it printed out null which was weird but the error stack points to this, mCamera.setPreviewDisplay(holder);
I'm running it on the android emulator but I turned on the camera and tested it in the camera app which worked.
You have no code to test you have a camera. Make sure you have a camera before doing anything else with it.
In this code I am looking for the only camera or the camera facing the back ...
public int getCameraId() {
Log.d(TAG, "getCameraId()");
int cameraId = -1;
// Search for the back facing camera (or any camera)
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_BACK || numberOfCameras == 1) {
Log.d(TAG, "CameraInfo.CAMERA_FACING_BACK = "
+ (info.facing == CameraInfo.CAMERA_FACING_BACK));
cameraId = i;
break;
}
}
return cameraId;
}
public static Camera getCameraInstance(int cameraId) {
Log.d(TAG, "getCameraInstance("+cameraId+")");
Camera c = null;
try {
c = Camera.open(cameraId); // attempt to get a Camera instance
Camera.Parameters cp = c.getParameters();
Log.d(TAG, "getCameraInstance("+cameraId+"): Camera.Parameters = "
+ cp.flatten());
} catch (Exception e) {
Log.d(TAG, "Camera.open("+cameraId+") exception="+e);
}
Log.d(TAG, "getCameraInstance("+cameraId+") = "+c);
return c; // returns null if camera is unavailable
}
The calling checks that cameraId returned from getCameraId is > -1 before calling getCameraInstance.
override the ondestroy() method and release your camera instance mcamera.release()
reference link http://developer.android.com/training/camera/cameradirect.html