My problem is similar to this one, How to update a widget every minute, however I only want to update TextView of the UI. I need access to the time so unfortunately can not simply use the DigitalClock view.
Ive been researching and have found ways to update every minute, but not on the minute so they are synchronised with the system clock (so they might be up to 59 seconds out of sync!)
The only ways I can think to do it are
(a) Run a handler (or timer) every second (which seems a bit like overkill if I only want to update every minute) Like this from the android.com resources
(b) Have a service running in background. (I'm not keen on this as I already have more important things running in the background)
(c) use Alarm Manager (again seems like overkill)
Seems to be such an easy thing to do, and yet...
Any advice appreciated
Mel
The accepted answer does not respond specifically to the question. The OP asks for a way to receive some sort of event on time (at the system clock minute and 00 seconds).
Using a Timer is not the right way to do this. It's not only overkill, but you must resort to some tricks to make it right.
The right way to do this (ie. update a TextView showing the time as HH:mm) is to use BroadcastReceiver like this :
BroadcastReceiver _broadcastReceiver;
private final SimpleDateFormat _sdfWatchTime = new SimpleDateFormat("HH:mm");
private TextView _tvTime;
#Override
public void onStart() {
super.onStart();
_broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context ctx, Intent intent) {
if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0)
_tvTime.setText(_sdfWatchTime.format(new Date()));
}
};
registerReceiver(_broadcastReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}
#Override
public void onStop() {
super.onStop();
if (_broadcastReceiver != null)
unregisterReceiver(_broadcastReceiver);
}
The system will send this broadcast event at the exact beginning of every minutes based on system clock. Don't forget however to initialize your TextView beforehand (to current system time) since it is likely you will pop your UI in the middle of a minute and the TextView won't be updated until the next minute happens.
You can try configuring a Timer to run a TimerTask that updates your TextView every minute (see its schedule method).
have you tried postDelayed()
This is what I used :
int secsUntilOnTheMinute=60-Calendar.getInstance().get(Calendar.SECOND);
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
updateSendTimesHandler.sendEmptyMessage(0);
}
}, secsUntilOnTheMinute*1000, 60000);
Related
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.
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
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.
I want to make a Notification that repeats every day at the same time, which is choosen by the user. The user has got also the possibility to decide wheater he will be nofified or not.
Is that possible with the Alarm Manager? Can I stop it or change the repetition with my settings? How can i make it possible that it stops automatically at a certain day?
Thanks a lot :)
Maybe you could you use a Timer with schedule:
http://developer.android.com/reference/java/util/Timer.html
Something like
this.timer=new Timer();
this.timer.scheduleAtFixedRate{
new TimerTask(){
public void run()
{
send_notification();
}
},
0,
864000000 // Every 86.400 seconds, aka 1 day
);
You'll have to experiment, but this should be a good start
I'd like to add a repititive taksk to a Service in my Android app. I've read about Runnable/Handler constructs, and about the Timer.scheduleAtFixedRate(). I'm wondering which one is the best approach.
I'm especially worried about the "scheduleAtFixedRate()" being run multiple times at once if execution takes longer than the interval. Or is that not possible?
How long is the interval? For this purpose, i think is good to use android AlarmManager.
It is for scheduling events on android, you can see a nice example here. And you can choose the method setRepeating instead set for repetive events.
static final long DELAY = 4000;
TimerTask task= new TimerTask (){
public void run(){
//do what you needs.
timer.shedule(this, DELAY);
}
}
Timer timer = new Timer();
timer.shedule(task, 0);
You can try this.