Crash camera after 3 shots - android

After I take 3 shot camera stops responding (crashes).If I try to restart application camera state == locked and default camera gets locked too.
Example code:
private Runnable SimpleShot=new Runnable()
{
#Override
public void run()
{
int i=0;
while (i<7)
{
simpleShot();
try
{
Thread.sleep(1500);
} catch (InterruptedException e)
{
e.printStackTrace();
}
i++;
}
}
};
private void simpleShot()
{
//System.gc();
camera.takePicture(shutterCallback,rawCallback, this);
}
If I don't use thread camera doesn't response after 3rd shot too. Please Help.
In end method onPictureTaken, I call camera.startPreview();
LogCat http://pastebin.com/qDcthyNe
#Override
public void onPictureTaken(byte[] paramArrayOfByte, Camera paramCamera)
{
if(Utils.isSDAval() && Utils.PrepareAppFolder())
{
String path = Utils.APP_FOLDER+"/"+"APP"+"_"+Utils.getDate()+ CameraPrefsActivity.EXT_PIC;
try
{
FileOutputStream os = new FileOutputStream(path);
os.write(paramArrayOfByte);
os.close();
} catch (Exception e)
{
Utils.ShowInfo(this,getString(R.string.app_error_io));
e.printStackTrace();
}
Utils.ShowInfo(this,getString(R.string.app_shot_ok));
SharedPreferences main_pref = PreferenceManager.getDefaultSharedPreferences(this);
String string_format = main_pref.getString("pref_preview_time","0");
int timer_val = -1;
if(string_format.contains("0"))
{
timer_val = -1;
}
if(string_format.contains("1"))
{
timer_val = 1;
}
if(string_format.contains("3"))
{
timer_val = 3;
}
if(string_format.contains("5"))
{
timer_val = 5;
}
if(string_format.contains("10"))
{
timer_val = 10;
}
if(timer_val > 0)
{
Intent intent = new Intent(this,CameraPreview.class);
CameraPreview.setupActivity(path,timer_val);
startActivity(intent);
}
}
else
{
Utils.ShowInfo(this,getString(R.string.app_error_sd));
}
paramCamera.startPreview();
}

This guy had the same problem and apparently its the emulator, try running it on a real device it worked for him.

Related

Using flashlight cancels SensorListener and accelerometer

I'm developing an application where if the screen of the phone is facing up the flashlight starts blinking. If the screen of the phone is facing downwards the flashlight is suppose to stop blinking. For detecting whether if the screen of the phone is facing up or down I'm using the accelerometer. The code to detect the orientation of the screen is here:
#Override
protected void onResume() {
super.onResume();
smAccelerometer.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
smAccelerometer.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent event) {
int type = event.sensor.getType();
if (type == Sensor.TYPE_ACCELEROMETER) {
float gz = event.values[2];
if (mGZ == 0) {
mGZ = gz;
} else {
if ((mGZ * gz) < 0) {
mEventCountSinceGZChanged++;
if (mEventCountSinceGZChanged == MAX_COUNT_GZ_CHANGE) {
mGZ = gz;
mEventCountSinceGZChanged = 0;
if (gz > 0) {
Log.d(TAG, "now screen is facing up.");
Toast toast = Toast.makeText(MainActivity.this, "Up", Toast.LENGTH_SHORT);
toast.show();
flashlightFrequency();
} else if (gz < 0) {
Log.d(TAG, "now screen is facing down.");
Toast toast = Toast.makeText(MainActivity.this, "Down", Toast.LENGTH_SHORT);
toast.show();
}
}
} else {
if (mEventCountSinceGZChanged > 0) {
mGZ = gz;
mEventCountSinceGZChanged = 0;
}
}
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
As you can see from this code, whenever the screen is facing up i call the method flashlightFrequency() which turns the flashlight on and off in intervals:
public void flashlightFrequency() {
String myString = "0101010101";
int frequency = 2000; //Delay in ms
CameraManager camManager;
String cameraId = null; // Usually front camera is at 0 position.
camManager = (CameraManager) getApplicationContext().getSystemService(Context.CAMERA_SERVICE);
try {
cameraId = camManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
for (int i = 0; i <= myString.length(); i++) {
if (i == myString.length()) {
flashlightFrequency();
}
if (myString.charAt(i) == '0') {
try {
camManager.setTorchMode(cameraId, true);
} catch (CameraAccessException e) {
e.printStackTrace();
}
} else {
try {
camManager.setTorchMode(cameraId, false);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(frequency);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The accelerometer works fine and I'm able to detect the orientation of the screen UNTIL I call the method flashlightFrequency(). When the flashlight starts the phone no longer registers motions. It seems like the flashlight cancels the SensorListener. Whenever the flashlight is turned on I can't use the accelerometer to detect the orientation of the screen.
The solution was to implement the flashlightFrequency() in an IntentService class. By doing that the flashlight will run in the background and therefore not interfere with the accelerometer.

Get Video Play Time android from videoplayer

I write this function to get video time . This functions works fine but when I backpress then it throws exception .
public void videoTimer ()
{
try
{
running = true;
final int duration = mVideoView.getDuration();
thread = new Thread(new Runnable()
{
public void run()
{
do
{
tvVideoTimer.post(new Runnable()
{
public void run()
{
int time = (duration - mVideoView.getCurrentPosition()) / 1000;
tvVideoTimer.setText(getTimeString(mVideoView.getCurrentPosition()));
}
});
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
if (!running) break;
}
while (mVideoView.getCurrentPosition() <= duration);
}
});
thread.start();
}
catch (Exception e)
{
e.printStackTrace();
}
}

how to implement button with flashlight blinking code in android studio

i want to add flashlight Blinking mode in android studio with a button. but i don't know that how can i put a code and how to implement this code with a button. because i want that if i press button then flashlight start blinking.
can anyone tell me that how can i implement this code with a button?
String[] list1 = { "1", "0", "1", "0", "1", "0", "1", "0", "1", "0" };
for (int i = 0; i < list1.length; i++) {
if (list1[i].equals("0")) {
params.setFlashMode(Parameters.FLASH_MODE_ON);
} else {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
}
}
You can use this code for blink i make this as method :
private void BlinkFlash(){
String myString = "010101010101";
long blinkDelay =50; //Delay in ms
for (int i = 0; i < myString.length(); i++) {
if (myString.charAt(i) == '0') {
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
} else {
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
and it will call like this :
BlinkMode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BlinkFlash();
}
});
Hope this will work for you and yeah make string long if you want blink long time then
All of these below codes put inside any where in your activity/fragment:
Status, handler, Camera variables:
boolean isOn[] = {false};
boolean[] isBlinking = {false};
Handler handler = new Handler();
CameraManager camManager = null;
String cameraId = null;
Handle button click listener on your activity/fragment:
camManager = (CameraManager) view.getContext().getSystemService(Context.CAMERA_SERVICE);
buttonFlash.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isBlinking[0]){
BlinkMode(view);
isBlinking[0] = true;
} else {
if(splashThread2 != null){
splashThread2.interrupt(); // stop blinking
OffFlash();
}
isBlinking[0] = false;
}
}
});
Blinking method:
Thread splashThread2;
private void BlinkMode(View view){
splashThread2 = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(100);
if(!isOn[0]){
OnFlash();
isOn[0] = true;
} else {
isOn[0] = false;
OffFlash();
}
}
} catch (Exception e) {
}
}
};
splashThread2.start();
}
Handle when goback
#Override
public void onStop() {
super.onStop();
if(splashThread2 != null){
splashThread2.interrupt(); // stop blinking
OffFlash();
}
// todo check null exception
}
#Override
public void onPause() {
super.onPause();
if(splashThread2 != null){
splashThread2.interrupt(); // stop blinking
OffFlash();
}
// todo check null exception
}
On/Off Method for new version of Android:
private void OnFlash(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
cameraId = camManager.getCameraIdList()[0];
camManager.setTorchMode(cameraId, true); //Turn ON
isOn[0] = true;
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
}
private void OffFlash(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
cameraId = camManager.getCameraIdList()[0];
camManager.setTorchMode(cameraId, false); //Turn ON
isOn[0] = false;
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
}

App Freezes and Crashes when trying to Blink the Flashlight

there Folks! And Here it goes another Question.. from me..
I'm making a flashlight app. In the app there are two buttons, one is for turning on/off flash (flashlight_switch) and the other one is for blinking the flash With a single tap on the Button (sos_switch) at medium speed. The flash on/off works perfectly, but when i press the SOS button the app freezes and crashes. And also how can I turn off the SOS. I'm a beginner so it would be very nice that you explain the answer in depth. Please ignore Any typos if there are. The App is tested on Galaxy S3 and LG G3 and no luck on both of them.
Here is the complete code:
Java:
FlashlightActivity:
public class FlashlightActivity extends Activity {
ImageButton flashlight_switch;
ImageButton sos_switch;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flashlight);
flashlight_switch = (ImageButton) findViewById(R.id.flashlight_switch);
sos_switch = (ImageButton) findViewById(R.id.sos_switch);
flashlight_switch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
if (Flash.getTorch()) {
flashlight_switch.setImageResource(R.drawable.flashlight_switch_on);
} else {
flashlight_switch.setImageResource(R.drawable.flashlight_switch_off);
}
}
});
sos_switch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (SOS.getSOS()) {
sos_switch.setImageResource(R.drawable.sos_on);
} else {
sos_switch.setImageResource(R.drawable.sos_off);
}
}
});
}
}
Flash:
class Flash {
private static boolean flashOnOff = false;
private static boolean sosOnOff = false;
public static Camera camera;
private static Camera.Parameters params;
public static boolean getTorch() {
if (flashOnOff)
off();
else
on();
return flashOnOff;
}
public static boolean getSOS() {
if (sosOnOff)
offSOS();
else
onSOS();
return sosOnOff;
}
private static void on() {
if (!flashOnOff) {
if (camera == null || params == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
int a = 10;
}
}
try {
camera.setPreviewTexture(new SurfaceTexture(0));
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
flashOnOff = true;
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static void off() {
if (camera == null || params == null)
return;
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
camera.release();
camera = null;
flashOnOff = false;
}
private static void onSOS() {
Thread t = new Thread() {
public void run() {
try {
int delay = 50;
int times = 10;
for (int i=0; i < times*2; i++) {
if (flashOnOff) {
on();
} else {
off();
}
sleep(delay);
}
} catch (Exception e){
e.printStackTrace();
}
}
};
t.start();
}
private static void offSOS() {
Thread t = new Thread();
t.stop();}}
Thanks In Advance!
Update:
I have updated my flash.java. It does not crash now but still the SOS don't work and also the sos switch freezes. I can't figure it out now. Please help!!!! as soon as possible!
You should not sleep Thread.sleep(blinkDelay); the thread because it is main thread need to update UI.you should use a different thread for SOS on
And Your SOS on function is in recursive infinite loop plz edit it. You are calling ON infinite time recursivly
Make Flash class ON / OFF method to public and make few changes in SOS's on method on(); to Flash.on and off to Flash .off
Flash.java
class Flash {
private static boolean flashOnOff = false;
public static Camera camera;
private static Camera.Parameters params;
static Thread t;
public static boolean getTorch() {
if (flashOnOff) // turn off flash
off();
else // turn on flash
on();
return flashOnOff;
}
private static void on() {
if (!flashOnOff) {
if (camera == null || params == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
int a = 10;
}
}
try {
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.setPreviewTexture(new SurfaceTexture(0));
camera.startPreview();
flashOnOff = true;
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static void off() {
if (camera == null || params == null)
return;
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
flashOnOff = false;
}
public static void onSOS() {
t = new Thread() {
public void run() {
try {
int delay = 50;
while (true) {
if (t.isInterrupted())
break;
getTorch();
sleep(delay);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
public static void offSOS() {
if (!t.isInterrupted()) {
t.interrupt();
off();
}
}}
FlashlightActivity.java
public class FlashlightActivity extends Activity {
ImageButton flashlight_switch;
ImageButton sos_switch;
boolean isStart = false;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flashlight);
flashlight_switch = (ImageButton) findViewById(R.id.flashlight_switch);
sos_switch = (ImageButton) findViewById(R.id.sos_switch);
flashlight_switch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
if (Flash.getTorch()) {
flashlight_switch.setImageResource(R.drawable.flashlight_switch_on);
} else {
flashlight_switch.setImageResource(R.drawable.flashlight_switch_off);
}
}
});
sos_switch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!isStart){
Flash.onSOS();
isStart = true;
sos_switch.setImageResource(R.drawable.sos_off);
}else{
Flash.offSOS();
isStart = false;
sos_switch.setImageResource(R.drawable.sos_on);
}
}
});
}
}

A delay of a Few seconds when trying to power on Led flash

Im trying to power on the led flash, but the led flash powers on after a delay of a few seconds.
I have a built in torch in my phone, and when I click it it the flash turns on immediately.
Whats the problem here?
Heres my code:
private void processOnClick() {
if (manuName.contains("motorola")) {
DroidLED led;
try {
led = new DroidLED();
led.enable(true);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
if (mCamera == null) {
try {
mCamera = Camera.open();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
mCamera = Camera.open();
} catch (Exception e) {
e.printStackTrace();
}
if (mCamera != null) {
final Parameters params = mCamera.getParameters();
List<String> flashModes = params.getSupportedFlashModes();
if (flashModes == null) {
return;
} else {
if (count == 0) {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
mCamera.setParameters(params);
mCamera.startPreview();
}
String flashMode = params.getFlashMode();
if (!Parameters.FLASH_MODE_TORCH.equals(flashMode)) {
if (flashModes.contains(Parameters.FLASH_MODE_TORCH)) {
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(params);
} else {
// Toast.makeText(this,
// "Flash mode (torch) not supported",Toast.LENGTH_LONG).show();
params.setFlashMode(Parameters.FLASH_MODE_ON);
mCamera.setParameters(params);
try {
mCamera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
count = 1;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
if (mCamera == null) {
return;
}
}
private void processOffClick() {
if (manuName.contains("motorola")) {
DroidLED led;
try {
led = new DroidLED();
led.enable(false);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
}
}
}
DroidLED class:
import java.lang.reflect.Method;
import android.os.IBinder;
class DroidLED {
private Object svc = null;
private Method getFlashlightEnabled = null;
private Method setFlashlightEnabled = null;
#SuppressWarnings("unchecked")
public DroidLED() throws Exception {
try {
// call ServiceManager.getService("hardware") to get an IBinder for the service.
// this appears to be totally undocumented and not exposed in the SDK whatsoever.
Class sm = Class.forName("android.os.ServiceManager");
Object hwBinder = sm.getMethod("getService", String.class).invoke(null, "hardware");
// get the hardware service stub. this seems to just get us one step closer to the proxy
Class hwsstub = Class.forName("android.os.IHardwareService$Stub");
Method asInterface = hwsstub.getMethod("asInterface", android.os.IBinder.class);
svc = asInterface.invoke(null, (IBinder) hwBinder);
// grab the class (android.os.IHardwareService$Stub$Proxy) so we can reflect on its methods
Class proxy = svc.getClass();
// save methods
getFlashlightEnabled = proxy.getMethod("getFlashlightEnabled");
setFlashlightEnabled = proxy.getMethod("setFlashlightEnabled", boolean.class);
}
catch(Exception e) {
throw new Exception("LED could not be initialized");
}
}
public boolean isEnabled() {
try {
return getFlashlightEnabled.invoke(svc).equals(true);
}
catch(Exception e) {
return false;
}
}
public void enable(boolean tf) {
try {
setFlashlightEnabled.invoke(svc, tf);
}
catch(Exception e) {}
}
}
I took this code from some answer around stackoverflow.
Thanks for your assistance!
Do you get high latencies with the motorola?
It's just a guess, but the DroidLED constructor calls expensive system initializations.
Couldn't you do this?
public class MyWidgetClickHandler {
private DroidLED = null;
public MyWidgetClickHandler(string ManuName) {
// This is slow. It will run once at initialization.
if (ManuName != null && ManuName.toLowerCase().contains("motorola"))
DroidLED = new DroidLED();
}
public void processOnClick() {
if (DroidLED != null)
DroidLED.enable(true);
else
; // ... TODO
}
public void processOffClick() {
if (DroidLED != null)
DroidLED.enable(false);
else
; // ... TODO
}
}
There could be so much more. For example you could create a LED interface with enable and isEnabled, and have two implementations for it. One would be DroidLED and the other the CommonCameraLED.
With this it looks like this:
public class LEDFactory {
public static LED createLED(string ManuName) {
if (ManuName != null && ManuName.toLowerCase().contains("motorola"))
return new DroidLED();
else
return new CommonCameraLED();
}
}
public class MyWidgetClickHandler {
private LED myLed = null;
public MyWidgetClickHandler(string ManuName) {
myLed = LEDFactory.createLED(ManuName);
}
public void processOnClick() {
myLed.enable(true);
// NOTHING TO DO
}
public void processOffClick() {
myLed.enable(false);
// NOTHING TO DO
}
}
You could also create a Thread for initialization so that phone won't start slow.
I just came across the same problem and found a solution, but i made my tests using a Samsung Galaxy S2. This code should work on every device.
Profiling each one of the functions, i found that some calls necessary to setup the camera, sumed up to 500ms in delay, making a strobe effect impossible.
My solution was to move all those functions to a separate function i call when i want to get the camera, and reduce the "turn on" code just to the call to Camera.setParameters(). By doing this, the delay came down to only 4ms.
For example (reduced code just to to prove the point):
// First get the camera for your app (Keep this variables as class
members so the live between functions)
private void acquireCamera()
{
try
{
// Get camera
cam = Camera.open();
// This is not on your code but you should do it for compatibility
mSurfaceTexture = new SurfaceTexture(0);
cam.setPreviewTexture(mSurfaceTexture);
cam.startPreview();
camParams = cam.getParameters();
}
catch(IOException e)
{ /*...*/ }
}
// Then turn on / off as many times you want.
private void setTorch(boolean on)
{
camParams.setFlashMode(on? Camera.Parameters.FLASH_MODE_TORCH : Camera.Parameters.FLASH_MODE_OFF);
cam.setParameters(camParams);
}
// Finally release the camera when you`re done
private void releaseCamera
{
camParams = null;
cam.stopPreview();
mSurfaceTexture = null;
cam.release();
}

Categories

Resources