How to keep flash on when activity goes to background - android

I am developing a very simple flashlight application, while I have successfully achieved what I was looking for, I would like to perform it that way I want it to. Currently my flashlight remains on while my activity is active, as soon as I hit the home button to minimize the activity flashlight turns off. I want the flashlight to stay on and turn off only when I click the turn off button in my activity.
I also want something like that if the flashlight is active and user hits the home button to minimize the activity, Turn Off button to be displayed in the notification bar.
Please guide me.

Please try to use bellow code.
public class CustomFlashLight {
private static CustomFlashLight instance;
private static Camera mCamera;
public static CustomFlashLight getInstance() {
if (null == instance) {
instance = new CustomFlashLight();
}
return instance;
}
public static boolean checkFlashAvailaibility(Context context) {
boolean flag = false;
try {
flag = context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FLASH);
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
public static boolean turnOnLight() {
boolean flag = false;
try {
mCamera = Camera.open();
if (mCamera != null) {
Parameters params = mCamera.getParameters();
if (Build.MODEL.equals("GT-P1000")) {
params.setFlashMode(Parameters.FLASH_MODE_ON);
} else {
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
}
mCamera.setParameters(params);
mCamera.startPreview();
mCamera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});
flag = true;
} else {
flag = false;
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
public static boolean turnOffLight() {
boolean flag = false;
try {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
flag = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
}

Got solution.
#Override
public void onBackPressed() {
super.onBackPressed();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
if (camera!= null) {
camera.release();
camera= null;
}
Log.d("Camera","Back Pressed");
}
And removed all the code from onStop() and onPause() method.

Related

android detect if other app try to open camera show alert dialoge

I want to create an application, and it needs to know when the camera is turned on by other app, whether the camera application is open or if a third party app is using the camera
how can i detect that if other app is try to open the camera . if other app try to open the camera i want to receive any broadcast before open the camera how can i do this.
i have also try this.
public boolean isCameraUsebyApp() {
Camera camera = null;
try {
camera = Camera.open();
} catch (RuntimeException e) {
return true;
} finally {
if (camera != null) camera.release();
}
return false;
}
but its alwys return true.
There is no broadcast for camera open or not but Camera Avaiability Listener in Camera2 Api, use below code
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
manager.registerAvailabilityCallback(new CameraManager.AvailabilityCallback() {
#Override
public void onCameraAvailable(String cameraId) {
super.onCameraAvailable(cameraId);
//Do your work
}
#Override
public void onCameraUnavailable(String cameraId) {
super.onCameraUnavailable(cameraId);
//Do your work
}
}, mHandler);
}
its only 21 and above
For below 21 you can use your code
public boolean isCameraInUse() {
Camera c = null;
try {
c = Camera.open();
} catch (RuntimeException e) {
return true;
} finally {
if (c != null) c.release();
}
return false;
}

How to make thread sleep according to progressValue of seekBar

I am making app like this. Everything is working fine but there is a little problem. I want to change duration of Flash (ON/OFF) of Flash Light by value of progress bar. Means thread should sleep by duration progressValue.
When onProgressChanged method is called, I want call method flash_toggle_times(final int delay) to change value of sleep(delay) everytime progressValue is changed.
public void onProgressChanged(SeekBar seekBar, int progressValue, boolean fromUser) {flash_toggle_times(progressValue);}
Here is code for flash_toggle_times(SeekBar seekbar, int progressValue, Boolean fromUser)
public void flash_toggle_times(final int delay) {
mCamera = Camera.open();
final Parameters p = mCamera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
Thread t = new Thread() {
public void run() {
try {
// Switch on the cam for app's life
if (mCamera == null) {
// Turn on Cam
mCamera = Camera.open();
try {
mCamera.setPreviewDisplay(null);
} catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
}
while(positionON )
{
if(delay > 0){
toggleFlashLight();
sleep(delay);
}
}
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
} catch (Exception e){
e.printStackTrace();
}
}
};
t.start();
}
public void turnOn(){
if (mCamera != null) {
// Turn on LED
mParams = mCamera.getParameters();
mParams.setFlashMode(Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(mParams);
}
lightON = true;
}
public void turnOff(){
// Turn off flashlight
if (mCamera != null) {
mParams = mCamera.getParameters();
if (mParams.getFlashMode().equals(Parameters.FLASH_MODE_TORCH)) {
mParams.setFlashMode(Parameters.FLASH_MODE_OFF);
mCamera.setParameters(mParams);
}
}
lightON = false;
}
private void toggleFlashLight() {
if (!lightON) {
turnOn();
} else {
turnOff();
}
}
}

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);
}
}
});
}
}

Unable to kill a Thread in Android

I have created a thread in a class, The code is as follows
private void startThread() {
if (t != null) {
t.interrupt();
}
isFlashOn = true;
t = new Thread() {
public void run() {
try {
try {
SurfaceView surfaceView = (SurfaceView) activity
.findViewById(R.id.surfaceViewCam);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
// surfaceHolder.addCallback(this);
camera.setPreviewDisplay(surfaceHolder);
} catch (Exception e) {
e.printStackTrace();
}
camera.startPreview();
for (int i = seekBarManager.preferenceManager
.get_duration(); i > 0 && !this.isInterrupted(); i--) {
isFlashOn = true;
setBlinkToggle();
sleep(seekBarManager.preferenceManager.get_delay());
if(isFlashOn==false){
break;
}
}
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
I stop the thread in a method
private void stopThread() {
if (t != null) {
t.interrupt();
//t.
isFlashOn = false;
}
}
The problem I am facing is, The for loop in the thread seems to be running even after the successful call of Interrupt()
Any help here would be greatly appreciated!
Updated Code
t = new Thread() {
public void run() {
Boolean isStop = false;
try {
try {
SurfaceView surfaceView = (SurfaceView) activity
.findViewById(R.id.surfaceViewCam);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
// surfaceHolder.addCallback(this);
camera.setPreviewDisplay(surfaceHolder);
} catch (Exception e) {
e.printStackTrace();
}
camera.startPreview();
for (int i = seekBarManager.preferenceManager
.get_duration(); i > 0 && !isStop; i--) {
isFlashOn = true;
setBlinkToggle();
sleep(seekBarManager.preferenceManager.get_delay());
}
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
} catch (Exception e) {
e.printStackTrace();
isStop=true;
//notify();
return;
}
}
};
Purpose of interrupt():
It just sets the interrupted flag to true. After interrupt() has been called the Thread.currentThread().isInterrupted() starts to return false. And that's all.
Another case is if interrupt() is called while the thread is blocked in an invocation of one of the methods that throw InterruptedException, then that method will return throwing the InterruptedException. And if thread's code just "eats" that exception, then the thread will still continue running.
So the correct approach should be to periodically check the interrupted flag. And if interrupted status is detected then just return ASAP. Another common option is not to use Thread.interrupt() at all, but some custom boolean instead.
See the below link for safe stop of thread:-
http://www.java2s.com/Code/Java/Threads/Thesafewaytostopathread.htm

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