Handler to show the countdown timer is not reliable - android

I am developing an App where I show the countdown timer. To countdown the time I am using Handler class. Once the countdown timer reaches certain time the Alarm goes off. My problem is as below,
Initially I show the timer time as 04:00:00. Once it reaches 00:00:00 then the Alarm goes off. The Alarm code is working fine. But the timer display is not reliable. It works fine until I keep the App open. If I close the App (using Home or Back) or lock the device and open App again then the timer shown is not the correct one (delaying a lot, but still alarm works on-time). (But it works sometimes very fine under the same scenario). But whenever I ping the device to the system for checking the Log in eclipse that time all works fine!!!!!!!
1. I want to know whether I am using the Handler properly or not
2. (or) Is going out of the App or locking the device causing the problem
Below is my Handler code,
Handler digiHandler;
// Method to initialize the time and define the Handler
public void initialize(int hourstime,int mintime,int sectime){
hour = hourstime;
min = mintime;
sec = sectime;
digiHandler = new Handler();
handleRunnable = new Runnable(){
public void run(){
updateTimes();
}
};
}
public void startUpdateTheread(){
digiHandler.postDelayed(handleRunnable, UPDATEDELAY);
}
// Method to update the timer times
private void updateTimes(){
timerText = String.format(timerFormat,hour,min,sec );
-------------------------
-------------------------
-- code for incrementing the time ---
--------------------------
--------------------------
--------------------------
startUpdateTheread();
}
Please give the suggestions
Thanks
Edit:
When I observed the log it shows that to countdown 1 second of timer sometimes it is taking 1 minute time. The log is as below,
09-21 21:09:18.965: DEBUG/DigitalTimer(7656): timerText**:04:22:54
****long difference here****
09-21 21:10:19.308: DEBUG/DigitalTimer(7656): timerText**:04:22:53
..................................................................................
..................................................................................
..................................................................................
09-21 21:10:23.314: DEBUG/DigitalTimer(7656): timerText**: 04:22:49
**--long difference here ---**
09-21 21:11:22.604: DEBUG/DigitalTimer(7656): timerText**:04:22:48
It is happening always. So I can rule out that locking/coming out of an App is causing the problem. Seems I need to tweak the Handler part of the code.

The problem is that if the activity dies, then so does the thread it spawned, I recommend creating a service to handle this since such timers can be long i imagine (over 4 minutes) and in that time, you need the application to not die.
take a look at http://developer.android.com/reference/android/app/Service.html and let me know if that seems like a good enough solution.

Related

Is it possible to stop the Notification Chronometer after it reaches a certain value (0:00)?

I'm using NotificationCompat.Builder with .setUsesChronometer(true).setWhen(Instant.now().toEpochMilli() + timeDifference.toMillis());.
The setWhen()-timestamp is in the future, so the Chronometer value got a - before the time and it counts down.
When it reaches the timestamp, it continues to change and the value is now positive (counts up).
Is it possible to deactivate the Chronometer at 0:00 or stop it before it starts to count up?
I've found setChronometerCountDown(true) but it's API24+ (I need 19), Android Studio says it cannot resolve this method and I think it just removes the minus sign when counting down so that does not help me.
If the answer is no, is there an alternative?
Updating the notification every second would affect the battery drain I guess?
I'm using RemoteViews in my Notification so the Chronometer of RemoteViews could be an alternative but I can't find a way to stop that one either.
I used a handler to stop the chronometer.
mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mCollapsedView.setUsesChronometer(false);
mNotificationManagerCompat.notify(1, mNotificationBuilder.build());
}
}, timeDifference.toMillis());
It would still be helpful to get some feedback for my solution. I don't have much experience with Android.

Android send commands to obd every sec or less for real time data

For now my app have a chat that comunicate via bluetooth with an OBD port in the car.
Now i want upgrade my project for real time information, so i want create a method that repeat some Array with a list of commands and repeat the sendMessage(message) every sec or 500 millisec (something for real time data).
There is some bestway to do that?
I have my Activity with 4 EditText for showing data and a Button with "start scan" and if pressed it becomes a "stop scan" and interrupt the infinite loop of commands.
In the same time i need to take back data and show results in the EditText.
EDIT
Or just use an AlarmManager?
EDIT 2
With this code not work properly because send only the first message after 5 sec and the second it lost...
How can i send all the commands into ArrayList one at a time every t millisec?
public void repeatCommand(){
for (final String command : commandArray){
final Handler handlerTimed = new Handler();
handlerTimed.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms
sendMessage(command);
}
}, 5000);
}
/*String message = "010C\r";
sendMessage(message);*/
}
Sorry I didn't write android code for so long but I had your case so long ago.
You have to define a Service and start it in foreground with RETURN_STICKY and then write a handler with timer which execute your code per second (or what you like!). Then you can broadcast your result or how you want to communicate with your activity and use it.
Then start service and stop it with your button.
PS:
1. As far as I know alarmManager is not a good idea in this case.
Somehow you have to be sure that your Service will not be killed by android.

Android Eclipse - If button isn't pressed within 'x' seconds then

Trying to figure out how to do this, basically my App requires a button to be hit and hit multiple times, it counts how many times you hit it and if you don't hit one within a certain space of time it will display a message.
I just can't figure out how to get the 'If button isn't pressed within 'x' seconds then...' part, I've tried if(imagebutton1.isPressed()) statement but it checks it instantly when the actvity starts, I just want it to check 'X' amount of seconds after the button was last pressed.
ANy help is appreciated thanks.
In your case you would need to record the last time the button was pressed
Then add a updated while statement
In c++
Int presses;
Int timelimit; //the seconds between each press (you can use a chronometer but this is simpler but less accurate (and no decimals)
Int lastpressed; //need chronometer for more accuracy or decimals)
Int ammountpassed; //time since you pressed it
If(imagebutton1.isPressed())
{
Bool Started = Yes;
Presses++;
While(!imagebutton1.isPressed()&&ammountpassed<TimeLimit)
{
Ammountpassed++;
};
};
If (ammountpassed>=timelimit)
{
If (presses>=highscore)
{
DisplayMsg " Number of presses" presses; "! New highscore!";
};
Else(presses<highscore)
{
DisplayMsg "not fast enough! Number of presses" presses; "!" };
};
};
You will have to tweak it a bit to fit your needs ("displaymsg" I for think is the actual function so you might have to change that but there's the logic :)
I recommend hand typing this as I belive I may have made a few error but nothing adding a semi colon or 2 won't fix ;)
Hope it helps :) Good Luck :)
Every time the user hits the button you can post a message on the handler's queue with your text message to be displayed and the appropriate delay time (and remove previous messages). Therefore if the delayed time exceeds without any press the thread will execute the handler's message. Lets say you want to post to the main handler a message to be executed in delay number of milliseconds, then in your activity you would need to hold the reference to the handler and create a Runnable where the necessary text message will be displayed:
Handler mainHandler = new Handler(getMainLooper());
Runnable runnable = new Runnable(...);
In your OnClickListener of the button you would need to execute only:
#Override
public void onClick(View v) {
mainHandler.removeCallbacksAndMessages(null);
mainHandler.postDelayed(runnable, delay);
}

How to set up a timer for an android game ?

I want to programm a game for Android.
Play principle: The user should have a short time to choose the correct answer.
My problem is the combination between the input (choosing the answer) and the time (countdown). I tried to run a thread, but the thread isn't stoppable. So the user gives the answer, the next activity will be shown and after a while (when the "timer" becomes 0) the activity will be shown again.
How could I implement this in a correct way?
Should I use Thread, Handler, CountDownTimer ?
You can keep a running timer using this on init:
Timer updateTimer = new Timer("update");
updateTimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
updateGUI();
}
}, 0, 1000);
long startTime = System.currentTimeMillis();
Then in a Thread:
//Clock update
currentTime = System.currentTimeMillis() - startTime;
SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
clock.setText(sdf.format(currentTime));
clock.invalidate();
You could stop the Thread with a boolean inside or outside as you please?
Okay, I don't know the specific libraries to use, and I haven't done any thread programming myself, but I would think of the program as a state machine. I hope it helps :/
Set up a boolean userHasAnswered = false.
Set up a specialized listener (e.g. touch listener for some button) for answers.
If the listener gets an appropriate response from the user, set userHasAnswered = true.
When question loads up, start the thread which counts down.
If user fails to give ans when the time reaches zero, just call loadNextQuestion().
In your thread, do periodic checks every few units of time to see if userHasAnswered == true, and if it is true, then call updateScore() and loadNextQuestion().
You may want to have a look at alarm manager

how to set themes continuously in android

My problem is make a function to set up themes in my application every 00:00 AM if there are new themes. As I know, to do this problem we must use a loop.
Here is my code:
private void updateThemes() {
Thread time = new Thread() {
public void run() {
int time = 0;
while(time > 86400000) {
//invoke method or start new activity
}
}
};
}
Please help me - Thanks.
Running a thread and waiting for a full day is not going to work. What if the phone is shutdown? What if the user switches to another app and your app is closed by Android because it needed the resources? Besides, it's not very battery friendly either.
You'd better use the Android AlarmManager to set the times at which you would like to check for updates. Also specify a BroadcastReceiver in your app that will receive and process the alarms. There's an example application that does this here or check this post for more info.

Categories

Resources