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
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.
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.
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
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.
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);