I am making an android flashlight app. I it has two activities, a main activity and a settings activity where the camera led can be toggled on and off. It also has another class where all the camera changes are handled like opening it, releasing it, and turning the light on and off.
I kept getting errors when turning on the led based on shared preference settings because I was not opening and releasing the camera in the correct activity lifecycle stages. I fixed the issues by releasing the camera when onPause is called in either activity and turning the led on or off (based on shared preference settings) when onResume is called in either activity.
The problem I am having now is that if the led is on, it turns off briefly when switching from one activity to the other because I have to release the camera and then open again in the new activity. Can anyone help me figure out a way to eliminate this problem? Where should I open and release the camera? I have tried releasing it in on destroy but the led stays on when the app is minimized to the background, which is undesirable. Thanks for any suggestions.
In both main and settings activity I have:
#Override
protected void onResume() {
super.onResume();
if (sp.getBoolean("LED_TOGGLE_CB", false) == true) {
flash.turnFlashOn();
}
}
#Override
protected void onPause() {
super.onPause();
flash.killCamera();
}
In the Flash class I have:
void getCamera() {
if(camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch(RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
void turnFlashOn() {
getCamera();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
}
public void killCamera() {
if (camera != null) {
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
}
}
Related
I have a live wallpaper that just draws triangles, very simple, and runs smoothly all time. After testing found that when I open the camera to take pictures the phone freezes for about 10 seconds, then the camera opens and the wallpaper crashes and the message "Unfortunately, Live Wallpaper has stopped." appears. Also found that when I open any barcode scanner app the problem raises again because the scanner uses the camera too. Seems the problem raises when the camera app runs. Any ideas what's causing it?
hi #Bullet Camera is just open ones, if it open through any other apps then, you can can not access your camera, Solution is that, where you use camera please release that after no used.
main problem is that, in your app (app in that you are using camera) , so , you release camera after used.
like following :
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
}
when you need
private void releaseCameraAndPreview() {
if (camera != null) {
camera.release();
camera = null;
}
}
or
public void stopCamera() {
if (cameraDevice != null) {
cameraDevice.stopPreview();
cameraDevice.setPreviewCallback(null);
cameraDevice.release();
cameraDevice = null;
System.out.println("in to the stop video");
}
}
My app is using camera. i'm having a CameraActivity class and CameraFragment class,
CameraFragment is responsible for releasing the camera:
#Override
public void onPause() {
super.onPause();
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
My app crashed while taking a picture. for some reason the camera was not released. now i can't get the camera object nowhere! Also the android Camera app is not working with an error "Can't connect to the camera"
now i know that the camera is a singleton object and only one app can get it in a time.
what i don't understand is why onPause didn't run and how can i protect the camera instance better?
Also if something like that happens, how can i force release the camera object? it it a good idea?
sadly i don't have the information why the app crashed at the first place.
Thanks for your help.
Roy
This should help:
private static void unCaughtExceptionHandler() {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(final Thread thread, final Throwable ex) {
ex.printStackTrace();
releaseCamera();
System.exit(0);
}
});
}
I am using a Camera, and I call the open method on it in onCreate in an activity. When the activity is destroyed, I release the Camera. However, a fragment in the activity may be using the Camera (for example, making the flash blink repeatedly), so when the orientation changes from portrait to landscape, for example, the Camera is released (because the activity is destroyed) and the reference is set to null, causing a NPE to be thrown from the fragment. How do I keep the reference to the Camera during orientation change (so that the flash keeps blinking) and release the Camera when the activity is destroyed (for example, when the user clicks the Back button)?
public static Camera camera = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
if (camera == null) {
camera = Camera.open();
if (camera == null) {
Log.e(LOG_TAG, "Unable to get back-facing camera.");
finish();
}
}
// ..
}
#Override
protected void onDestroy() {
if (camera != null) {
camera.release();
camera = null;
}
super.onDestroy();
}
Try this android:configChanges="keyboardHidden|orientation"
For api 13 or higher android:configChanges="keyboardHidden|orientation|screenSize"
As of api 13 screen size also changes when a device switches between portrait and landscape mode
So this way your activity will not be destroyed during orientation change
I'm trying to create a Glass GDK app that uses the Camera service to show a preview. Unfortunately, I currently have a bug where a RuntimeException is thrown when trying to open a Camera using Camera.open(). I only encounter this bug when opening the activity through a voice trigger, not by selecting the app from the "launcher" menu.
Is there a difference in how an Activity is launched through this menu versus the voice trigger?
Some of the relevant code is below.
#Override
public void onCreate(Bundle savedInstanceState) {
mGestureDetector = createGestureDetector(this);
super.onCreate(savedInstanceState);
ctx = this;
act = this;
setContentView(R.layout.activity_main);
preview = new Preview(this, (SurfaceView)findViewById(R.id.surfaceView));
((FrameLayout) findViewById(R.id.preview)).addView(preview);
preview.setKeepScreenOn(true);
}
#Override
protected void onResume() {
super.onResume();
try {
if (camera == null) {
Log.d(TAG, "Opening a camera on resume.");
camera = Camera.open();
preview.setCamera(camera);
camera.startPreview();
}
} catch(java.lang.RuntimeException e) {
Log.e(TAG, e.getMessage());
}
}
#Override
protected void onPause() {
if(camera != null) {
camera.stopPreview();
preview.setCamera(null);
Log.d(TAG, "Releasing a camera on pause.");
camera.release();
camera = null;
}
super.onPause();
}
#Override
protected void onDestroy() {
if(camera != null) {
camera.stopPreview();
preview.setCamera(null);
Log.d(TAG, "Releasing a camera on destory.");
camera.release();
camera = null;
}
super.onDestroy();
}
Since it doesn't work when using the voice trigger, it sounds like a possible race condition where the microphone isn't released by the time your activity is displayed on the screen.
Can you try an approach that uses exponential back-off to capture the camera? Basically try to capture the camera and if you get an exception, try again after a short amount of time, increasing the wait time slightly for a fixed number of attempts.
Please also consider filing a bug on the issue tracker, especially if you can reliably find out how much of a delay is needed before the camera/mic can be acquired.
The problem is caused by the delay between the voice recogniser closing event and the camera open event, which is causing a memory overload.
To avoid the problem when launching the app which will be triggered with voice,
pause the app for certain time (1000 Milli seconds will do) from opening the camera soon.
In the below code I am delaying my QR scanner to open from opening for 1000 Milli seconds. This works fine for me. If you want a you can increase the time interval.
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
intent = new Intent("com.google.zxing.client.android.SCAN");
startActivityForResult(intent, 0);
}
};
// sleeper time
handler.sendEmptyMessageDelayed(0, 1000);
I have classic android app with camera preview (common implem that can be found in many tutorials [marakana etc.]) that is supposed to take picture in a given time interval. Threading and killing threads is done, errors such "method called after release" are handled. But sometimes the well-known error 100 occurs. I accepted the fact that it happens and tried to handle it too. I implemented ErrorCallback and its onError method where the current camera object is released and instantiated a new one as written in official documentation.
But (with no surprise) it is not enough. New camera is maybe wrongly allocated because an message "CameraDemo has been exited unexpectedly" appears now.
I've read many docs and examples in hope, that a proper proceeding will be somewhere explained but no one has such problem apparently. So I would like to ask what else should I do beside releasing and creating new camera? Here is the code:
ErrorCallback CEC = new ErrorCallback()
{
public void onError(int error, Camera camera)
{
Log.d("CameraDemo", "camera error detected");
if(error == Camera.CAMERA_ERROR_SERVER_DIED)
{
Log.d("CameraDemo", "attempting to reinstantiate new camera");
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release(); //written in documentation...
camera = null;
camera = Camera.open();
}
}
};
Shortly - if I release and recreate camera in onError callback then RuntimeException Method called after release (takePicture) is raised. So should I somehow assign the surface holder to camera again or recreate the surface holder too?
It would be enough to direct me e.g. to some forums, where it is described or solved, etc. Thanks for any help.
In my app to handle the camere i use this :
public void onResume() {
super.onResume();
if(mCamera == null)
mCamera = getCameraInstance():
}
public static Camera getCameraInstance() {
mCamera = null;
try {
mCamera = Camera.open();
Parameters parameters = mCamera.getParameters();
mCamera.cancelAutoFocus();
mCamera.setPreviewCallback(yourPreviewCb);
mCamera.startPreview();
mCamera.setParameters(parameters);
mCamera.autoFocus(yourAutoFocusCB);
} catch (Exception e) {
//TODO
}
return mCamera;
}
The mCamera = null in the getCameraInstance() is just to be sure there is no camera running at all.
I think you need to recreate a complete camera, not just open it with the
camera.open();
Set this in the onResume or in the error callback, depending on your needs.
This is how I fixed it, here is a sample of code, think you get the idea:
private Camera camera;
// code...
public Camera getCameraInstance() {
Camera camera = Camera.open();
// code...
camera.setErrorCallback(new ErrorCallback() {
#Override
public void onError(int error, Camera camera) {
if(error == Camera.CAMERA_ERROR_SERVER_DIED) {
releaseCamera();
startCamera();
}
}
});
return camera;
}
protected void startCamera() {
if(getCamera() == null)
setCamera(getCameraInstance());
refreshCamera();
}
protected void releaseCamera() {
if (getCamera() != null) {
getCamera().release();
setCamera(null);
}
}
public Camera getCamera() {
return camera;
}
public void setCamera(Camera camera) {
this.camera = camera;
}