How to initiate events based on stopwatch timer? - android

Basically I'm working on an application that alerts drivers how long they have been driving. It requires alerts at certain times.
At the moment I'm using a chronometer that displays time passed.
As one hour passes I need a message to appear on screen saying 'Hour Passed'.
As 2 hours passes I need another message saying 'Hour Passed' and a further message saying 'A 15 minute break is required'. Then a button needs to appear that allows the user to start a break which until starts a new chronometer.
When the break is complete at 15 minutes, a button needs to appear that says 'continue driving' and the original chronometer displaying driving time needs to continue from the time it was at before the break (2:00:01).
As you can see all the functionality is relatively similar, based on time events.
I'm guessing I need to use some sort of if statements that are initiated when the chronometer reaches a certain time but I'm basically stuck on how to make the application do the required functionality when the chronometer reaches a certain time.

Try taking a look at the AlarmManager class to run an intent a certain amount of time after the time the stopwatch is started.

Try using the alarm manager with a pending intent.Create a receiver that catches the pending intent action and do whatever you want to do.
You can either register a broadcastreceiver from your app when it is started(preferred way in your case) or create a broadcastrecievr and create a intent filter in the manifest file...In this case the event would be catched even if your app is not running.

Related

Increase points even app is closed android

I am new in android and I don't know how to do this, I want to create a background service, There is two main component in my app one is Button (Start Earning) and another is TextView (Points). I want to create service like if User Open app and Click on Start Earning Button then the the points in TextView wants to Increase Continuously For 1 Hour (100 Points In 1 Hour). then after 1 hour I want to stop that service automatically even if app is closed
Example Is In This Screenshot.
Pls Help Me I Search Every Where (Google,Stackoverflow,Github,etc.) But I Don't Get Any Answer.
The service you are looking to use here is a broadcast service, which broadcast how much time has been passed after button has been pressed. So you can have a broadcast service, which has a CountDownTimer for counting down 1hr time. Then you can broadcast the message (containing the points) after a particular time (like after each minute or seconds or after an hour) based on your need. In your fragment/activity you will have an broadcast listener, which will listen to the broadcasted messages (points) and update the UI. You can refer to https://stackoverflow.com/a/22498307/5309486 answer for the implementation details.

Listen to app wake up event / schedule a wake up event

I'm trying to schedule event. For example, i'd like for something to happen 1 hour from now. For this i used handler postdelayed. Unfortunetly, this doesn't work as expected. I guess the reason is that android puts my app to some kind of sleep state, so the timer freezes at some point, and keeps counting from the point stopped when the device is back to use. This causes the event to occur at unknown time, greater than the time expected.
Now, i have two ways to solve this and i'd like to know how to implement each one:
Schedule to wake the device at a specific time and then excecute the event. I don't know how to schedule a wake up (and do it efficently).
Excecute the event as soon as my app wakes, if the time of execution has passed (i can use date and time to verify if the time passed). What i miss here is how to listen to wake up event.
And for my general knowledge about android sleep policy: Does android put services and activities to sleep automatically? how, if so, any messaging app keeps listening to new messages?
Thanks in advance for any help :)
You have to use Alarms,
Alarms give you a way to perform time-based operations outside the lifetime of your application.
android has 4 types of Alarms :
ELAPSED_REALTIME—Fires: the pending intent based on the amount of time since the device was booted, but doesn't wake up the device. The elapsed time includes any time during which the device was asleep.
ELAPSED_REALTIME_WAKEUP—Wakes: up the device and fires the pending intent after the specified length of time has elapsed since device boot.
RTC—Fires: the pending intent at the specified time but does not wake up the device.
RTC_WAKEUP—Wakes: up the device to fire the pending intent at the specified time.
Read this pages Alarms

Android: How to make multiple CountdownTimers work on background?

I have an App where the user can create multiple countdown alarms. Each one has it's own name, time to count, ringtone, etc.
I extended the CountDownTimer to hold each alarm setup and created a Singleton manager to manage all the alarms.
Everything is working fine until I leave the App.
The counters don't actually die. They have a weird behavior. After starting a counter:
1) if I press back key until the home screen and then power off the screen the alarm will trigger as it should.
2) if I press the home button then turn off the screen it will trigger only if I open the app.
3) if I just turn off the screen while still on the app it will trigger as soon as I turn on the screen.
I expected trouble because for that kind of thing I need to use Services, Handlers or other stuff like these.
The problem is, I'm new to Android and after reading a lot about it, I couldn't find a solution.
As far as I understood I should use Services, but it can have only one instance. How would I work with multiple alarms?
Is there other way of doing it?
I need a way to start each alarm and tell the system to keep counting no matter what happens! (and to call an Activity when it finishes)
Any help?
Is there other way of doing it?
If your goal is to alert the user of events in the future, regardless of whether your app is running, dump all your CountdownTimer logic, and switch to AlarmManager. It is specifically designed for this sort of scenario. You can set up an AlarmManager event for each timer, to get control when the end time is reached.
Also note that you will need to maintain information about your registered events in a file or database:
so users can add and remove them, and
so you can set up AlarmManager again if the user reboots their device
and to call an Activity when it finishes
Users may reject your app for that behavior. Not everyone wants to be interrupted in the middle of what they are doing with their device. Please allow this to be configurable, so the user can opt for something less intrusive, like a Notification.
You should replace your CountdownTimers with AlarmManager (as in CommonsWare's answer), after setting it up it will trigger your function to execute on specified time, here is official guide:
http://developer.android.com/training/scheduling/alarms.html
Soon you will find that after device reboot your alarms are lost, you need to restart them by catching android.intent.action.BOOT_COMPLETED broadcast.
Also you should not do a lot of work in your alarm onReceive, you should pass information to some other component like IntentService, to make it safe while device is asleep you should use WakeLock (sample project).
[edit] ---- you should also store your alarm/ringtone related data in some persistant storage, you can use for it shared preferences, or (more work) sqlite database.
I you really want to use timer (i.e. when you want to show countdowns on screen):
You don't have to have multiple timers to show multiple countdowns.
Everything you have to do is just put the target time into some collection, or event put it into the View.setTag().
Then you have timer (let say 1s tick) - on every single tick you have to iterate over all your gauges, check the target time and current time, parse the number and adjust the gauge.
However - as the timers works on separate (non main) threads - you will have to use handler or something like that.
If you want to just set some alarms - take the CommonsWare's answer - it's good one.

Android Communicate with AlarmManager

I am not sure how to describe my Problem. Basically I want to write an app, which reminds the user after a specific time (e.g. 1hr) of something. Unless he does not confirm the reminder, it will nag him every 10 mins, after the initial hour has passed.
Until the reminder pops up for the first time there will be 4 stages (eg. every 15mins), which should be shown inside the activity (eg with colors green, yellow, orange, red).
I implemented the reminder with a Broadcast Reciever and the AlarmManager, so far so good. But how can I check how long its been since the Alarm was set to find out in which stage I am? If the Activity is running in the foreground while the stage changes, the change should be made visible instantly. If the activity is started while the alarm is still counting down, the current stage should also be shown.
Anyone can point me in the right direction on how to do this in a good way, since I am still fairly new to Android.
Thank you.
[So far I basically followed this tut http://www.vogella.de/articles/AndroidServices/article.html]
You may want to maintain an int that represents the state of your counter. You can make it a member variable in your Activity, and you may want to persist it in shared preferences as well. To pass status change notifications from the alarm service back to your Activity, send an Intent. Your activity need not check up on the alarm counter; it can simply wait for the intents to roll in.

Notification when app not used for more than certain period

Is there a way to send a notification to the user that app has been downloaded but a certain task from the app is not yet complete even after certain period - say a month. One way is a background service which should come alive every month in this case, check the app state (in sharedprefs) and then send a notification. Is there some other easier way in Android without writing custom service.
Here's how I would do it. Schedule an alarm using the AlarmManager to go off a month from today. That alarm can trigger some code inside of a Receiver or otherwise to check whether the said event has occured. If it hasn't, you can then show a Dialog or whatever.
In order to wake up your app after some amount of time (in your example a month) you're going to have to set an alarm. You can use AlarmManager for that. If all you're going to do is check SharedPreferences, you can do that in a broadcast receiver. You can send your notification there.

Categories

Resources