I currently have a class named LocationCheck.
public class SpeedCheck {
Here the location is retrieved every 3 seconds and is ongoing until the user stops it. To start checking for locations, the class is called in the Main Activity:
startLoc = new LocationCheck(this);
What i am wondering is if the code needs to be in a Service class rather than just an ordinary class (like it currently is). It works so far with no issues, but i may be misunderstanding the concept of Services etc and could be unaware of problems it may face over checking over a long period of time (fairly new to Android dev).
I have looked into Background Service for location updates, but with FusedLocationProvider (which i am using) it is only possible to receive several updates over an hour. This would not be helpful as i need an update every 3 seconds.
Any advice would be greatly appreciated.
If you need to keep checking location in background then use service else you can just simply use it in activity. Simply stop the service when you no longer need it because it will consume more battery if left running in background.
Related
What is the best way to keep user's location in sync with server,even after the app is terminated?
here is what I found this far
using a foreground service. I already tested that but it's battery consuming, and sometimes it's killed when you lock the phone or turn off the screen.
using work manager. I also tested it, it sends the location every 15 mins,but so unreliable, and it stopped sending after a while.
Geofencing. I read that Geofencing api gets location updates more often, every couple of minutes or so, but I haven't tested it.
LocationListener. There is a method called onLocationChanged, but I don't know how would it work in background.
is there something like a broadcast receiver that will be fired only when location changed by a margin? I think this would be an optimized solution.
I am building an app that uses a feature similar to facebook nearby friends (which is stopped working long time ago) or something like tinder to display nearby people.
Currently I need this for android, but I will need it for IOS as well, I am developing a flutter app.
I already used a similar method in my app which is working:
I used foreground service to record the location, the battery consumptions are related to the frequency of location request not really the foreground service itself. indeed using LocationListener is a good option
then I am checking the foreground service regularly using workmanager and restart it when needed.
best
As discussed in the comments above, I don't really think Android allows for you to get location updates in the background even when the application is not active.
I recommend you instead try to query for location as soon as the app starts, and quickly follow up with whatever actions you need to make with it. As an option, you can also keep track of location history by caching their location as they interact with the app, in case you want to keep the database as fresh as possible.
Here's some pseudo code as a simple example:
class MainActivity : AppCompatActivity() {
override fun onCreate(..) {
queryForLocation(..)?.let {
doSomething(it)
cacheLocation(it)
} ?: Log.d(TAG, "Location = null")
}
override fun onDestroy() {
queryForLocation(..)?.let {
cacheLocation(it)
} ?: Log.d(TAG, "Location = null")
}
I'm developing a location aware app. This app will start tracking users when they are in their workday. These are the requirements:
The service should run on a regular basis (every 30 or 45 min).
It won't matter if the service does not trigger at the same basis everytime.
The service needs to upload data to our firestore db.
I doesn't need to be triggered on specific conditions (data is on, phone is charging, etc...)
I need this to run even if the user restarts his phone.
We may need to track the distance traveled by the user. (This is not a requirement per se, but it may be a feature someday)
I know there are a lot of ways to achieve this, but I have not decided which is the option that best fits my scenario. This is what I've thought so far:
Foreground service combined with BroadcastReciever in case the phone is rebooted
Background service using the new jetpack's Workmanager.
Which will the best solution? Do you think there is a better solution than those?
Thanks!
Was thinking create a GPS location tracker so when they are in work premise as well as outside it kinda shows.
Then consider adding the number 5 of the above. Like you said there could be mire awesome solutions than these so lets wait for options.
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 :)
My application is based on Google Map and Location which includes client-server communications. Apart from all that, periodically I want to update the user location to web server. I gave thought myself and ended up with below two scenarios,
First One :
I use Service class to fetch user location periodically (considering 2-3 hours once) and update to server. Ideally I want to avoid this! Because just to upload user location its not good to run the service all the time is what I feel.
Second Thought :
I can use IntentService to fetch the user location periodically (considering same 2-3 hours) and update to web server. Here IntentService will be invoked by an AlarmManager. That is every 2-3 hours once alarm manager will start IntentService.
But I feel using AlarmManager for 2-3 hours once is not a good idea too.
I want to understand which one will be efficient and more relevant! Whether this scenario can be implemented in any other approach? If so help me do it!
Thanks in advance...
I have a repeated task(Task A) to do when I receive a broadcast in my application. I need to know which one is better between these options to do the repeated task?
A Timer in a standalone class and does the Task A repeatedly on timer expiry?
An android background service doing the Task A.
what are the pros and cons in choosing the above methods?
what are the pros and cons in choosing the above methods?
You seem to assume that all possible "Task A" implementations are created equal. You also seem to assume that all periods (one millisecond to one century) are created equal. Neither of these are true.
It is impossible to answer your question in the abstract, and it would take a few dozen pages to explain all the possibilities.
My task need to update the location to my java class variable which is not an activity and has to update to a webserver using HTTPS
If you need to periodically update a Web server with the device location, and the polling period is sensible (e.g., every 30 minutes), your best option is to use AlarmManager and a Service. I wrote a LocationPoller which was designed for this scenario, which another developer has improved upon. Just bear in mind that it may not be possible to determine the device's location at any given moment, so you need to have a "timeout" mechanism in case you cannot find the location, since finding the location keeps the CPU (and GPS radio, where relevant) powered on. LocationPoller has such a "timeout".