Android Timer is called twice - android

Hey guys
I'm trying to develop a little slide show in android. I've implemented the timer with a timertask and as expected the "run"-method is called everytime after the delay. But, however, when the delaytime has passed, the run method is called twice, so that the slide show slides two pictures instead of one.
Can anyone help me to solve this problem? Heres some code for better understandig what i've done.
public void startTimer() {
if(timer == null) {
timer = new Timer();
}
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
timerHandler.post(new Runnable() {
#Override
public void run() {
Log.d("Hier herein", "Timer abgelaufen");
}
});
}
}, 7000, 7000);
}
The startTimer()-Method is only called once, so I really don't understand, why the function is called twice.
Thanks in advance :D

Related

Why "DISCOVERY_FINISHED" Message printed twice?

I want to Search Bluetooth Device Every three seconds.
so, I used Timer like this.
public void SearchingDevice() {
m_BTAdapter.startDiscovery();
m_timer = new Timer(true);
TimerTask timerTask = new TimerTask() {
public void run() {
m_BTAdapter.cancelDiscovery();
m_BTAdapter.startDiscovery();
}
};
m_timer.schedule(timerTask, 3000, 3000);
}
By the way, "android.bluetooth.adapter.action.DISCOVERY_FINISHED" Message
always printed twice..... why this message printed twice??
I used cancelDiscovery() only once...
please someone help me..!!
Thanks.
You should be careful with timer task. Maybe the problem is that you are not canceling task with activityLifecycle and each time you are creating a new one.
try:
#Override
protected void onPause() {
super.onPause();
m_timer.cancel();
}
can you paste the piece of code where you call SearchingDevice() method?

How can I control a timer in android?

I want to make an application about mini game.
Detail : In 2 seconds you must to answer a question if you don't answer or the answer is wrong -> Game Over . But if your answer is true the Timer will reset become 0 and countdown again with diffirent question.
I have already seen many code about timer in website but I don't understand clearly about it :(
So I want to ask : How can i set up a timer run only 2 seconds and how can i reset it and continue with a new question ?
Please help me.
you can use CountDownTimer in android like this:
public class Myclass {
myTimer timer =new myTimer(2000,1000);
public void creatQuestion(){
timer.start();
//method you init question and show it to user
}
public void getUserAnswer(/*evry thing you expected*/)
{
//if answer is true call timer.start()
//else call timer.onFinish(); to run onfinish in timer
}
public class myTimer extends CountDownTimer {
public myTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
// you can update ui here
}
#Override
public void onFinish() {
this.cancel();
//fire game over event
}
}
}
i hope it make you satisfy
I've done something similar using Thread/Runnable.
Thread t = new Thread(new Runnable() {
public void run() {
final long startTime = getTime();
final long maxEndTime = startTime + 2000L;
try {
while (shouldContinueWaiting()) {
if (getTime() > maxEndTime) {
throw new TimeoutException();
}
sleep();
}
} catch (InterruptedException e) {
handleInterrupt();
} catch (TimeoutException e) {
handleTimeout();
}
}
boolean shouldContinueWaiting() {
// Has the user already answered?
}
void handleInterrupt() {
// The user has answered. Dispose of this thread.
}
void handleTimeout() {
// User didn't answer in time
}
void sleep() throws InterruptedException {
Thread.sleep(SLEEP_DURATION_IN_MILLIS);
}
void getTime() {
return System.currentTimeMillis();
}
then you can start/restart the thread by:
t = new Thread(same as above...);
t.start();
and stop by:
t.interrupt();
We want to use the Timer class.
private Timer timer;
When you're ready for the timer to start counting -- let's say it's after you press a certain button -- do this to start it:
timer = new Timer();
timer.scheduleAtFixedRate(incrementTime(), 0, 100);
The first line is us creating a new Timer. Pretty standard. The second line, however, is the one I wanted you to see.
incrementTime() is a method that is called at the end of every "tick" of the clock. This method can be called whatever you want, but it has to return an instance of TimerTask. You could even make an anonymous interface if you want, but I prefer moving it off into its own section of code.
The 0 is our starting location. We start counting from here. Simple.
The 100 is how large a "tick" of the clock is (in milliseconds). Here, it's every 100 milliseconds, or every 1/10 of a second. I used this value at the time of writing this code because I was making a stopwatch application and I wanted my clock to change every 0.1 seconds.
As for your project, I'd suggest making the timer's task be your question switch method. Make it happen every 2000 milliseconds, or 2 seconds.
You can use a Handler.
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
//this will happen after 2000 ms
}
}, 2000);
Maybe this can help you:
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
// FIRE GAME OVER
handler.postDelayed(this, 2000); // set time here to refresh textView
}
});
You can fire your game over after 2000 milliseconds.
If you get the question correct -> remove callback from handler and reset it when the next question starts.

Get new value in edit box after N seconds without button in android

I am new in android and so, I need your help.
I want new and refreshed values in edit box such that after every 10 seconds without button click it brings changed value of PLC on edit box in my android device.
try this,
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
edittext.settext(yourtext);
}
}, 10000);
You can do this with a Timer for example. But think abaout, that this what You want to do is a Little bit battery intensive :
//create a Timer and TimerTask
private Timer timer;
private YourTimerTask yourTimerTask;
private void activateTimer(){
if(timer!=null){
timer.cancel();
}
timer = new Timer();
yourTimerTask = new YourTimerTask();
//this timer starts after 1 second and repeats every 10 seconds
timer.schedule(yourTimerTask, 1000, 10000);
}
private class YourTimerTask extends TimerTask {
#Override
public void run() {
runOnUiThread(new Runnable(){
#Override
public void run() {
yourEditBox.setText(yourText);
}});
}
}
I think with Edit box You mean an EditText? Anyway, this example is not tested, just from scratch. But it should give You an idea how to do.

Android: Updating textview at a some specific interval of time

Hello I am trying to update the textview at every certain time, but it only updates the first and then it force closes, here is the code:
try {
timer = new Timer();
timerTask = new TimerTask() {
#Override
public void run() {
//Download file here and refresh
updateRecSMSCount(count);
}
};
timer.schedule(timerTask,0, 3000);
} catch (IllegalStateException e){
}
void updateRecSMSCount(Integer count)
{
TextView numRecSMS=(TextView)findViewById(R.id.numRecSMS);
numRecSMS.setText(count.toString());
}
Can someone help please?
You can't access the UI from other thread than the thread that created the UI. The timer task runs in different thread. You can find solutions here: Updating the UI from a Timer
The most simple repair is:
void updateRecSMSCount(Integer count)
{
final TextView numRecSMS=(TextView)findViewById(R.id.numRecSMS);
numRecSMS.post(new Runnable()
{
#Override
public void run()
{
numRecSMS.setText(count.toString());
}
});
}
You can't update the contents of the view from another thread. You need to look at the Handler-class. See this and this.

how to stop/cancel android CountDownTimer

I'm extending the CountDownTimer class to obtain some custom functionality .In onTick() in case some conditions are met I call cancel() , expecting that will be the end of it, however the onTick() callback gets call until the the count down is reached . So how to prevent this from happening ?
CountDownTimer.cancel() method seems to be not working. Here's another thread without a solution Timer does not stop in android.
I would recommend you to use Timer instead. It's much more flexible and can be cancelled at any time. It may be something like that:
public class MainActivity extends Activity {
TextView mTextField;
long elapsed;
final static long INTERVAL=1000;
final static long TIMEOUT=5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextField=(TextView)findViewById(R.id.textview1);
TimerTask task=new TimerTask(){
#Override
public void run() {
elapsed+=INTERVAL;
if(elapsed>=TIMEOUT){
this.cancel();
displayText("finished");
return;
}
//if(some other conditions)
// this.cancel();
displayText("seconds elapsed: " + elapsed / 1000);
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, INTERVAL, INTERVAL);
}
private void displayText(final String text){
this.runOnUiThread(new Runnable(){
#Override
public void run() {
mTextField.setText(text);
}});
}
}
CountDownTimer is also working fine for me, but I think it only works if you call it OUTSIDE of the CountDownTimer implemetation (that is don't call it in the onTick).
Calling it inside also didn't worked.
I tried this code snippet, since most answers are saying you cannot cancel the timer inside its implementation, thus i tried using a handler inside onFinish. Old post but if anyone comes across this its helpful.
new Handler().post(new Runnable() {
#Override
public void run() {
timerTextView.setText("00:" + String.format("%02d", counter));
cancel();
}
});

Categories

Resources