Stop the flashlight after pressing back - android

I am using a thread to run the flashlight and I want to stop that thread after the back is pressed.
I used the following code to start the thread:
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Flashing...");
progressDialog.show();
thread = new Thread(MainActivity.this);
thread.start();
And the thread is doing:
public void run() {
isOn = false;
cam = Camera.open();
p = cam.getParameters();
try {
for (int i = 0; i < pattern.length; i++) {
if (isOn) {
p.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.setParameters(p);
Thread.sleep(pattern[i]);
isOn = false;
} else {
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
Thread.sleep(pattern[i]);
isOn = true;
}
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
cam.release();
handlerFinish.sendEmptyMessage(0);
}
private Handler handlerFinish = new Handler() {
#Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
}
};
I have tried this to stop, but there are only the progress dialog is dismissed but the flashlight is still working:
#Override
public void onBackPressed() {
super.onBackPressed();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.setParameters(p);
isOn = false;
thread.stop();
}
What can I do to achieve my goal (Stop the thread and flashlight after back is pressed)?

try this loop to stop the thread
boolean retry = true;
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
// try again shutting down the thread
}
}

Related

Flashlight Application With Timer

if(!isOn) {
imageButton.setImageResource(R.drawable.on);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
isOn = true;
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
I wanna add a timer to the flashlight app such that it keeps the flashlight on for the selected time
This is the code which works for me.
public void NotifyWithFlash(Context context){
boolean ShouldIGlow = true;
while(ShouldIGlow){
flashON();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
ShouldIGlow = false;
flashOFF();
}
}
}
public void flashON(){
Camera cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
}
public void flashOFF(){
cam.stopPreview();
cam.release();
}
I wanna add a timer to the flashlight app such that it keeps the flashlight on for the selected time so just set timer using Thread whatever you want as Thread.sleep(user decided period); for example Thread.sleep(5000);
You shouldn't use Thread.sleep() because it will block the UI. Instead you have android.os.Handler :
flashOn();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
flashOff();
}
}, 5000); // 5000 ms = 5 sec

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

Android App crashes after backpress with Handler and Camera

Android App crashes after backpress with Handler and Camera
I am trying to use camera for an SOS app , the code runs when we start the sos flash using the button click in order to keep the flash light running , I am using Handler with Post delay
the app crashes when we use backpress to go back to the previous activity
I have tried using handler.removeCallbacks(r); , onbackpress but still the app crashes
this is the code I am trying
public class sos extends Activity {
String myMorseString = "111000111";
int sleepTime;
Camera cam;
Handler handler;
Runnable r;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sos);
ImageButton button = (ImageButton) findViewById(R.id.Start);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startsos();
}
});
}
public void startsos() {
// new Thread() {
handler = new Handler();
r = new Runnable() {
public void run() {
if (myMorseString != null) {
for (int x = 0; x < myMorseString.length(); x++) {
if (myMorseString.charAt(x) == '2') {
cam = Camera.open();
sleepTime = 500;
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
}
// power off after signal
cam.stopPreview();
cam.release();
cam = null;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
if (myMorseString.charAt(x) == '1') {
cam = Camera.open();
sleepTime = 250;
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
// power off after signal
cam.stopPreview();
cam.release();
cam = null;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (myMorseString.charAt(x) == '0') {
cam = Camera.open();
sleepTime = 250;
Parameters p = cam.getParameters();
cam.setParameters(p);
//cam.startPreview();
cam.stopPreview();
cam.release();
cam = null;
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
handler.postDelayed(this, 10000);
}
// }.start();
};
handler.postDelayed(r, 10000);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onBackPressed() {
handler.removeCallbacks(r);
finish();
super.onBackPressed();
}
}
It's most likely crashing because the camera preview isn't being stopped when back is pressed. The Runnable is just being removed from the Handler.
That being said, you're also going to see another problem: creating a Handler from within an onClick() handler isn't creating a new thread. It's still creating a Handler which is bound to your main thread. The onClick() (and any view related callback) is called on the main (UI) thread. So the sleep() calls you are making in the Runnable are happening on your main thread, which is very bad.

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

How to unpause the thread in my Android surfaceview?

I actually can pause the thread correctly but when I press the unpause button
it doesn't resume. What am I doing wrong ?
public void pause() {
mRun = false;
while (true) {
try {
_thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
_thread = null;
}
public void unpause() {
mRun = true;
_thread = new GameBoardThread(this);
_thread.start();
}

Categories

Resources