Reputation: 718
I want to turn on/off the flash light in infinite loop, so when it turned on it should wait for 5 seconds and then turned off then wait 5 seconds to turned on again, and so on... how I can do that?
here is my code:
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// num = Integer.parseInt(n.getText().toString());
while(bl){
if(camera == null){
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
turnOn();
}
});
}
}).start();
}
else{
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
turnOff();
}
});
}
}).start();
}
}
}
});
Upvotes: 0
Views: 82
Reputation: 5420
I would recommend not using Thread
s in order to achieve this. Why not use the Runnable
class and post it with a delay via a Handler
? For example:
Handler handler = new Handler(); // make this a member variable of your class
boolean isOn = false; // make this a member variable of your class
final Runnable flashRunnable = new Runnable() {
@Override
public void run() {
if (isOn) {
turnOff();
isOn = false;
} else {
turnOn();
isOn = true;
}
handler.postDelayed(flashRunnable, 5000);
}
};
handler.postDelayed(flashRunnable, 5000);
If you need to run the code inside the Runnable
on the UI thread, you even call postDelayed
on a View
instead of creating a Handler
Upvotes: 1
Reputation: 18243
Try something like so, using Executors instead of (ugly) Thread.sleep():
boolean cameraOn = true
final Runnable runnable = new Runnable() {
@Override
public void run() {
// your logic here:
// if (cameraOn) ...
// else ...
// cameraOn = !cameraOn
}
};
Executors.newScheduledThreadPool(1).schedule(new Runnable() {
@Override
public void run() {
runnable.run();
}
}, 5, TimeUnit.SECONDS);
Upvotes: 0