I dont know how to go out from the loop - android

When I press this button:
case R.id.btlento:
Timer timers = new Timer();
timers.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
cameraOn();
},deloy1,poriod1);
Timer timers2 = new Timer();
timers2.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
cameraOff();
}
},deloy,poriod);
The methods cameraOn and cameraOff are:
private void cameraOff() {
// TODO Auto-generated method stub
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.release();
camera = null;
}
private void cameraOn() {
// TODO Auto-generated method stub
camera = Camera.open();
parameters = camera.getParameters();
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
}
and the variables are:
int deloy = 2000;
int poriod = 2000;
int deloy1 = 1000;
int poriod1 = 2000;
All this is to make the camera flash blink, but I don't know how break the loop, because never stops.
How can i stop the loop?

Use a flag,
// member variables
private boolean cameraIsFlashing = false;
private Timer onTimer;
private Timer offTimer;
// constructor & other stuff
// button click method
case R.id.btlento:
toggleCameraFlash();
break;
private void toggleCameraFlash(){
if(cameraIsFlashing){
stopFlashing();
} else {
startFlashing();
}
}
private void startFlashing(){
cameraIsFlashing = true;
// Start your timers
onTimer = new Timer();
onTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
cameraOn();
},deloy1,poriod1);
}
private void stopFlashing(){
cameraIsFlashing = false;
// Cancel / Stop your timers
onTimer.cancel;
}

call cancel() and purge() on thread timer to stop the thread.
as shown below.
private void cameraOff() {
// TODO Auto-generated method stub
if(timer != null){
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.release();
camera = null;
timer.cancel();// cancel and releases
timer.purge();
}
}

Make a variable for timer task instead of using anonymous class. First cancel timer task then cancel timer.

Related

How to detect if screen is touched in onTouchEvent()

I need to understand on how to detect if user has touched the screen.
Expected Result:-Whenever user touches screen it should skip Splash Screen and move to main activity.
Problem:-Whenever user touches the screen Splash Screen is skipped but in the background sleep(10500) in try block keeps running and as it elapses the Main Activity starts again i.e. it opens two times.
What have I done so far:-I tried do while loop and gave a condition,if the condition is satisfied(of Touch) then break.But I don't seem to get the correct working condition.
Splash Screen Code:-
#Override
protected void onCreate(Bundle splashState) {
// TODO Auto-generated method stub
super.onCreate(splashState);
setContentView(R.layout.splash);
ourSong = MediaPlayer.create(Splash.this, R.raw.splashsound);
ourSong.start();
Thread timer = new Thread() {
public void run() {
do
{
try {
//if(onTouchEvent(null))
// break;
sleep(10500);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
startActivity(new Intent("com.first.MAINACTIVITY"));
}
}while(false);
}
};
timer.start();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN) {
startActivity(new Intent("com.first.MAINACTIVITY"));
finish();
ourSong.release();
}
return super.onTouchEvent(event);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
ourSong.release();
}
If Statement is provided in the try block so if condition is satisfied it would break.But the condition is unknown to me.Need help with the condition.
Thanks.
private boolean isSplashRunning = true;
#Override
protected void onCreate(Bundle splashState) {
// TODO Auto-generated method stub
super.onCreate(splashState);
setContentView(R.layout.splash);
ourSong = MediaPlayer.create(Splash.this, R.raw.splashsound);
ourSong.start();
Thread timer = new Thread() {
public void run() {
do
{
try {
//if(onTouchEvent(null))
// break;
sleep(10500);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if(isSplashRunning)
startActivity(new Intent("com.first.MAINACTIVITY"));
}
}while(false);
}
};
timer.start();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN) {
isSplashRunning = false; //or in onPause
startActivity(new Intent("com.first.MAINACTIVITY"));
finish();
ourSong.release();
}
return super.onTouchEvent(event);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
isSplashRunning = false;
super.onPause();
finish();
ourSong.release();
}

How to stop running thread whenever I want and to start whenever I want

The below code is starting the thread only once, but I want to stop and start thread again by calling below method.
Thread th;
int t=45;
onstartbuttton()
{
th= new Thread(new callmymethod());
th.start();
}
onstopbutton()
{
}
public class callmymethod implements Runnable {
// TODO Auto-generated method stub
#SuppressWarnings("null")
#Override
public void run() {
// TODO Auto-generated method stub
while(t>-1){
try{
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
time_btn.setText(""+t);
if(t==0)
{
Toast.makeText(getApplicationContext(), "Thread over", Toast.LENGTH_SHORT).show();
}
}
});Thread.sleep(1000);
// Log.i("Thread", "In run"+t);
t=t-1;
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
Now I want to stop thread, so what I have to write in onstopbutton() method and how to start again by calling onstartbutton() method.
You need to add a flag to your thread indicating that it should stop running.
You can use an AtomicBoolean:
final AtomicBoolean flag = new AtomicBoolean();
onstartbuttton() {
th= new Thread(new callmymethod(flag));
flag.set(true);
th.start();
}
onstopbutton() {
flag.set(false); // indicate that the thread should stop
}
public class callmymethod implements Runnable {
public AtomicBoolean flag;
public callmymethod(AtomicBoolean flag) {
this.flag = flag;
}
#Override
public void run() {
int t = 45; // start back from 45
while(t>-1 && flag.get()){
// do as before
}
}
}

How to create timer for doing canvas rendering

public void BetTimerFuction()
{
int delay=0;
int period=200;
betTimer = new Timer();
betTimer.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
mHandlerBet.obtainMessage().sendToTarget();
}
}, delay, period);
}
Its my timer code but i didn't work with that timer in view class i m also using canvas .
When I use that timer in view class that timer get a number prosess is very slow when i click the button its increase the the integer two timers
I think u do the null first for your stop function.
public void StopBetTimer()
{
try
{
if(betTimer !=null)
{
betTimer.cancel();
betTimer=null;
}
}
catch(Exception e)
{
}
}
I revised you code because i think in that code no issue. But may be you didn't initialize properly to null your timer when you use first and also stop properly.
public void BetTimerFuction()
{
int delay=0;
int period=100;
betTimer = new Timer();
betTimer.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
mHandlerBet.obtainMessage().sendToTarget();
}
}, delay, period);
}
Here is for you stop function
public void StopBetTimer()
{
try
{
if(betTimer !=null)
{
betTimer.cancel();
betTimer=null;
}
}
catch(Exception e)
{
}
}

Two methods in a loop

private void cameraOn() {
// TODO Auto-generated method stub
camera = Camera.open();
parameters = camera.getParameters();
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
}
private void cameraOff() {
// TODO Auto-generated method stub
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.release();
camera = null;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent finis = new Intent (v.getContext(), MainActivity.class);
startActivityForResult(finis, 0);
}
I have these two methods and the button, and I want both methods work in a loop every second each, untill I press the botton for break the loop and go to another screen. These methods are for switch on and off the flash. So I want the flash blinking all the time until I press the button. I tried with threads but Im not able to do every method work just for one second, so I hope someone can help me. Thanks!!
I'm sure there's some kind if timer object you could use, but I would do something like:
long lastTime = 0;
boolean torchIsOn = false;
long currentTime = System.currentTimeMillis();
if (currentTime - lastTime >= 1000) {
if (torchIsOn) {
cameraOff();
torchIsOn = false;
} else {
cameraOn();
torchIsOn = true;
}
lastTime = currentTime;
}
That's just from the top of my head, so hopefully that works. ;)

how to stop the timer in android

This is my code following,I am changing some iamges dynamically in my image view.
public class LoadingScreen extends Activity{
public static Integer[] imageList={R.drawable.food_pics1,R.drawable.food_pics2,R.drawable.food_pics3,
R.drawable.food_pics4,R.drawable.food_pics5,R.drawable.food_pics6,R.drawable.food_pics7,
R.drawable.food_pics8,R.drawable.food_pics9};
Thread thread;
ImageView foodImageView;
final Handler myHandler=new Handler();
public int currentImageIndex=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.load_xml);
foodImageView=(ImageView)findViewById(R.id.imageView_food);
// final int i=0;
final Runnable runnable = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
animateImages();
}
};
final int delay=500;
final long period=1000;
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
myHandler.post(runnable);
}
}, delay, period);
}
private void animateImages() {
// TODO Auto-generated method stub
foodImageView.setImageResource(imageList[currentImageIndex%imageList.length]);
currentImageIndex++;
foodImageView.getAnimation();
}
I want to stop the timer and finish this activity after 20 secs.how can I do that.
Try using this,
View v = new View(this);
v.postDelayed(new Runnable(){
public void run() {
// TODO Auto-generated method stub
//cancel your animation and finish the Activity here.
finish();
}
}, (long) 20000.0);
You can say something like this :
timer.cancel();
timer = null;
Save the TimerTask instance in the class and invoke cancel on it.
Here's a tip I found very useful without using Java's Timer: Try synchronizing things in the UI thread, especially if you want to do UI tasks. Example:
... onCreate() {
getUiThreadHandler().post(new Runnable(){
if (canceled()) {
return;
}
// Actual work
...
// Invoke again after delay
getUiThreadHandler().postDelayed(this, 500);
});
Good luck

Categories

Resources