I have a background service that receives data roughly once per second from an external BT sensor. That data comes in, and gets sent to the UI using a broadcast intent/receiver. The live data is displayed in real time. This all works well right now.
What I need to do now and can't figure out: Have a button on the UI set up so that it starts a count of data coming in from the broadcast receiver (which is coming in roughly every second - but is not consistent enough to set a clock by), and stops after a given duration like 10 seconds. Every time new data comes in, it should be added to the total, and then after the duration of 10 seconds, the UI should be updated with the total, along with some message like "the total was 31".
This sounds easy, but using an async task - which seemed like the way to go - has been giving me trouble since I can't really set the task up to run a loop (afaik) since the looping timing needs to depend on the incoming broadcast receipt.
Any ideas on the best way to accomplish this if not via async task? I imagine the solution might be a simple one, but I'm not seeing it. Thanks for any help!
A Timer and TimerTask would help you with the timing issue and if you wanted to go all out you could implement the timer using ScheduledThreadPoolExecutor.
Related
I am trying to introduce auto-save functionality on one of my Android applications. The idea is that as the user inputs first name, last name and after a fixed interval I would like to save that information to the server before the user hits Next button. The final goal is to have something similar to the draft option in the Gmail app where your email information is automatically saved. So, if there is a timer that runs every 10 seconds, I will pass the information on the screen to the ViewModel and let it deal with the logic of saving the data to the server.
A couple of options I have explored are.
Execute recurring code with a specified interval using Handler.
PeriodicWorkRequest -- however this option has a minimum interval of 15 minutes which is a little too much for my use case.
AlarmManager -- This option runs even if your application is not currently running, In my opinion, this option can be an overkill.
I wanted to know if there are best practices/blogs around this and if anyone I on the wrong path or potential red flags with this approach.
you can make countdown for 10 second, when countdown is down save the data and call the countdown again.
when your activity is destroyed, so stop the countdown
The whole project consists in making an android application based on crowd sensing that collects data from volunteers (phase 1) and then based on the collected data, every user has a file in the server and the file would be separated into multiple online episodes and I will apply Artificial intelligence algorithms to make the data mining better.
For example, if in phase 1 I can determine that the volunteer is usually at home before 8am and he has no valuable information for me to analyse then the application wouldn't even send data to the server.
I'm still in phase 1, I'm trying to make an android application that starts running as soon as the user in connected to internet, it would send the data (battery, gps, activity...) to the server and based on the activity (walking, running...) it would determine when the next flow of data is sent. For exemple if he is walking then, the next time the data is sent to the server would be in 5 minutes.
While searching, I found many solutions on how to make an android application run in the background while keeping sensors collecting full time (high energy consumption) and the better solution would be to have a schedule for example every 5 minutes.
What I want to know is, is there an android studio solution to make the schedule dynamic? because it depends on the activity as I said before, so each time it collects information it schedules the next time the information is collected again (the next time we use sensors to collect the data then send it to the server).
I hope I made my point clear: what is always running in the background is an application that has a countdown to a specific moment; when that moment arrives the sensors are ON to collect data and send it to the server and that data is also used to make the next countdown (based on the activity data collected) and then the sensor are off until the countdown ends.
I would appreciate your suggestions.
Probably the best option for your project is AlarmManager. It can execute your code periodically or at a particular time, samples could be found here.
Also the app could be launched by system state event(like wi-fi on/off). To catch these events you need to use BroadcastReceiver, samples are here.
So you don't really need to implement countdown timers or background threads. Moreover manually created countdown background thread could be killed by the system at any time.
Regarding the problematic stated below I have come to a point where I need to make a decision on whether to:
Start a Service once that has an AlarmManager inside which then starts the query every 10 minutes. This Service will only be stopped if the user sets an "Onn-Off" Switch to "Off".
Use an AlarmManager to start an IntentService every 10 Minutes. This Service will then only be started when needed and closed afterwards
Which of these ways is better when it comes to:
- Ability to exchange data received by the Service (Or Intenservice) with other activities/services
- Battery usage
- Overall "good coding habits" ?
Thanks!
Original Question:
I am a pretty new Android Developer and have come across a situation that I do not know how to solve. I have already spent several days searching for a solution but could not find one.
While trying to develop my first app idea I have started playing around with receiving and parsing data from the internet. What I have achieved so far is generating a query that receives JSON data via an API and parses this JSON. All of which is done inside an AsyncTask. The received data is then shown on the screen.
However, for the purpose of my app idea, I need this to be done in the background. What I have thought of is:
Starting a Service that pretty much has the same logic as my Asynctask. Managed by an AlarmManager, this service then requests, receives and parses the data in a specific time interval.
Now the tricky part begins:
The data that I receive (let's say every 10 minutes) shall be used to change an alarm clock. So, as a simple example, let's say the user can set his alarm clock to 08:00 in the morning. The application then checks the current temperature every 10 minutes and changes the alarm clock time to 07:45 if the temperature is below 0° celcius because the user has to wake up earlier to clear the ice off his car.
Also, when "waking up" the application, the current (or rather the latest received) tempereture shall be shown in the UI.
What would be the best way to achieve this? I am having some issues regarding passing/receiving data from AsyncTasks/Services to/from Activities.
My first approach would be to start a single service from the MainActivity, passing some data to the Service (like the initial time the alarm shall start and the current location of the user). The Service then has two seperate AlarmManagers. One of which is set to perform the actual alarm (waking up the user in the morning) and the other manages the time interval of getting the data from the internet.
My questions:
- Does my train of thought make any sense at all so far?
- What is the best way to pass and receive data to/from a service? My best guess would be to use intents to pass and a broadcastreceiver to receive data from the service. would this make sense in this specific situation?
I fear that it is not welcomed to post questions without putting in any effort of your own before. Although I did not add any actual source code, I hope you can see that I have dealt with these questions for quite a while now but could not really start coding before I know the structure of the application.
Thanks in advance
Use AlarmManager to start an IntentService as often as necessary (in your example, it should be sufficient to start checking the temperature about two hours before the user plans to get up and maybe again after one hour and finally half an hour before the normal wakeup time. More often only in case of extreme weather conditions.
It's not necessary to check the temperature exactly at 03:33 a.m. so use
setInexactRepeating(), this will be easier on the battery.
See also Scheduling Repeating Alarms
Write the results to SharedPreferences and have one IntentService check 15 minutes before normal wakeup time if the user should get up right then. Cancel the normal wakeup alarm in this case. Communicating via SharedPreferences (think of a mailbox) and local (!) Broadcasts is a good idea - cheap and secure :)
I want to be reassured that I'm doing this the best practice way :
I have a list which order is changing on the server, therefore, I want every 20-30 sec. to perform a request to see if there were any changes in the order. So, I've created a Service which is bound to the Activity with the ListView, and the service every 20-30 sec. performs a request with an AsyncTask.
I chose to perform it with a Service because I want the list to be updated constantly, even when the application is in the background, And the AsyncTask is because I don't want it to be performed on the main thread.
Is this the right way to do it?
Thank you in advance,
Dan.
It will work, but your app will do a lot of unnecessary work. This will affect battery life. Besides that, according to documentation, if you use device radio, it stays full-powered at least for 20 seconds, which is also no good for battery. You have the following options:
Use Google Cloud Messaging. It will allow you to perform update only when this is really necessary.
If you don't want or cannot use GCM, follow this guide to optimize network access. Start with increasing the update interval (to 4 minutes at least).
I have been stuck on this issue for quite some time now.Have read the documentation and many tutorials and they just confuse me more.I hope someone will provide me a straightforward answer.It's really important.Thank you..
Ok ..so i want an activity to get some input from the user as and then send that string to a service.Then i want my service to run in a way so that i can use other applications while this one keeps running in the background.Also i don't want the service to keep running every second.What i want is for the service to get updated location of my current position every 10 minutes so i was thinkin if there could be a way to make my service to go to sleep n wake up evry 10 mins n check for updates.I don't want to show the update on the UI so i dont think i need to use an AIDL approach and also dont need to bind to the service.I js simply want to start the service as soon as the user enters the string and keep the service runing every 10 mins.I think it is really simple but m very confused.Please help.
You can start a service with a timer task of interval 10 min and do the desired task in the run method.
or by using handler with postdelaydmesage ..
check this