0

I'm developing an app bluetooth to communicate with a device. I have to send to that device a certain packet and that device respond to me in notify mode after a certain time. All works well, but I have to check if the response arrive to me in 3 seconds, and if it doesn't arrive in time, I have to send another command without waiting anymore to previous packet.

In what way Can I implement a timer in Android ?

I have thought to : 1- start timer when I send a packet 2- stop timer when the response arrive to me or if the msg was sended more 3 seconds ago the timer triggers function and it enable to resend other msg

I think to do it with handler and postdelay.

What do you think ? are there a better ways to implement this ?

Maybe a TimerTask ?

aeroxr1
  • 1,014
  • 1
  • 14
  • 36

1 Answers1

1

You can use CountDownTimer and start the timer when you send the packet to the device and in the onFinish() of CountDownTimer, you can check the response. If the response is not yet arrived, You can send another command to the device without waiting for the response anymore.

Geetha
  • 190
  • 9
  • Im scared of the following case : timer start, i receive the response, send other command, timer stop in less then 3 seconds because was started at first packet sends and never stopped and then I resend command in wrong time :/ – aeroxr1 Aug 19 '15 at 04:13
  • As soon as you get the response, you can always cancel the timer using cancel() if the timer is not finished yet. When you cancel the timer, mark the timer instance to null. So, you will be sure when you get the response, you can check for null for the timer instance. If the timer is not null and you get the response from the device, you can cancel the timer. CountDownTimer has got onTick() which you can use to check for the response periodically, say, if you set the timer for 3 seconds, you can check every one second whether the response has arrived or not. – Geetha Aug 19 '15 at 04:22
  • Example for CountDownTimer - http://androidbite.blogspot.com.au/2012/11/android-count-down-timer-example.html – Geetha Aug 19 '15 at 04:23
  • If you used this answer, can you please accept this answer? Thanks. – Geetha Aug 24 '15 at 04:26