Keep locationListener active between activities - android

I start an activity in my class Locator.java which starts a locacionListener Service. That activity writes positions to a database. I wonder if when i move to next screens(activities), positions will keep writing to the database, or I would need to go back to Locator.java to keep writting. The same when I minimize the application.
I have thouhgt about using a Service, but I want to be sure I need it.

As long as the service is started, and providing sufficient resources are available on the device, the service will continue to run in the background. Switching activities, minimizing or closing the app doesn't change that. It's up to you to formally stop the service.
The business logic for capturing location updates and storing them in the database should be implemented in the service however, and not in the activity. (The activity can be used to control the state of the service (stop-start), and to display data from the database, but the bulk of your location update / storing in database logic should be triggered from the service.
You can check the running services on your android device (Settings - Applications - Running Services). You should see your service, and the amount of time it has been running.
Depending on your requirements, a simple service will not cut it. If you for example you also want to capture location updates and store them in a database while the device is sleeping, you'll need to look at WakefullintentService

Related

Android: Firebase realtime database updated when app destroyed

I'm new to firebase realtime database, and have a basic question I cannot seem to find the answer to.
I need my Android app to keep track of changes in the database, so I understand I need to use addValueEventListener, with the onDataChange method. However will the method onDataChange, be called even if the app is destroyed? I need to be able to access the changes of the information in the database even if the app isn't running in the background, (for example the user force quits the app). This is because when the values reach a certain point, I want to show a pop up notification, so I need to able to read the values even when the app isn't running.
If the onDataChange is called even when the app is in the background, will this drain battery use since the phone is always listening for changes.
Sorry for the basic question, but I couldn't find the info.
Thanks!
...when the app is dead, is the EventListener still listeneing, and will onDataChange be called?
Event listeners are only active while the context they run in is active. For listeners you attach in an activity, that means they're active while the app is running. Even then Android might kill the listeners (or more accurately: the socket they use for communicating with the server) if the user isn't actively using the app.
If you want the listener to stay active longer, you can indeed consider managing the listeners in a background service. But even there, Android might close the listener to preserve battery life. That is the one thing to always keep in mind: if your use-case interferes with the user's preference (and most users are likely strongly prefer longer battery life over any specific app feature), it's unlikely to continue working in the long run.
A better approach is to combine listeners with Firebase Cloud Messaging for sending messages. FCM messages are more likely (though still not guaranteed) to be delivered when the user is not actively using the app, and you can use them to run some code of your app when they arrive. You'll want to use FCM's data messages for this, which is how most app deliver background updates.
You can also use an FCM data message to just wake up your own code, then have that code attach a listener, and get its updates. This type of behavior is known as sending a tickle, since all the data message does is waking the application code up.

Where do I store and how can I show on GUI kind of a volatile "global" variable?

In my android app there're an Activity and Service. The service is periodically doing some jobs in background, let's say, once in a 10 seconds -- pretty frequently. The service is always in background even when the Activity is closed/destroyed. And the services has a variable for saving a result of its calculations.
I want to display that variable on GUI and make the GUI show the current value of it in real time. The service, I'm not sure yet, but will be a normal service, not Intent Service due to some reason.
How can I show that variable on my GUI in real time? What's the approach, where should I begin? Is it enough to store it only in the service or should I also store it in more permanent storage as well such as Sqlite or SharedPreferences?
On startup or boot I want to reset the variable. So it's zero.
You can create a foreground notification (or probably simple "not autocancelable" notification) and update it's text every time you receive new data at your service.
If you also need to submit that data to activities you can use BroadcastReceiver
Because your Activity is not always running, and on startup you probably want to show the last-fetched value there, I would save the value in the SharedPreferences. When your Activity starts, you can retrieve the value, and you can also add an OnSharedPreferenceChangeListener. This will make sure that every time the Service finds and stores a new value, the Activity is notified.

Intent Service stays open after app closed

Ive created an app which needs to run an intent service while the application is closed if two values are out of sync(eg. 2 of 3). The intent service updates a text view within my application which will display the two values using a BroadcastReceiver.
Also the intent service is created in one activity but should be stopped in another. The two values are based on a GPS location update and that location being sent through a web service method. At points the GPS may update location and the web service might not due to limited connectivity to mobile data/wifi therefore leaving the values out of balance(1 of 3) and if the user closes the app this needs to continuously run until the value reaches 3 of 3(the GPS stops updating when app is closed).
The intent should run until the values are in sync again even if application has been closed. How would i keep this running whilst the app is closed and then stop it when the the values are in sync
Because an IntentService is like a Thread. It's designed to run aslong as it takes to finish onHandleIntent().
Use a regular Service and control it with stopService or stopself() if you want to manage the lifecycle.
edit: by the way, why do you mix asynctask and intentservices at all? Use one of them but dont mix it. AsyncTask handles all. Background Threading and processing in the mainUI. Anyway, for using GPS you should decide to use a regular Service and (maybe) create a Thread within the Services onStartCommand().

Keep android application running while in background

I have created an application in Android. This application should never die (even when sent to the background).
Currently, after a while the Service manager returns "No longer want..." and terminates it.
I've read that one solution whould be to create a service. However my application is way to complicated to be splitted into two functionality sets (one for the service and one for the application).
Is there any "trick" in order to keep my application running at all time?
Could I create a dummy service inside my application that might force the android to keep my application alive?
Is there any other way?
FYI: 1) It's a customized application that will not be released on the Market. 2) Handsets can't be rootted.
Thanks
You must create a Service to have a persistently running app, even after all your Activities have been sent to the background due to user pressing the Back button, answering a call, switching to another app, etc. You should review the Android Process Lifecycle which states that:
Sometimes an Activity may need to do a long-running operation that
exists independently of the activity lifecycle itself. An example may
be a camera application that allows you to upload a picture to a web
site. The upload may take a long time, and the application should
allow the user to leave the application will it is executing. To
accomplish this, your Activity should start a Service in which the
upload takes place. This allows the system to properly prioritize your
process (considering it to be more important than other non-visible
applications) for the duration of the upload, independent of whether
the original activity is paused, stopped, or finished.

how to structure my app to run in background

I am new to Android, and I need some advices for start up.
I want to build an application, which will show up, when the user gets into some hot situation.
By hot situation I mean:
the GPS/cell coordinates are in known zone;
known Bluetooth device detected;
known Wi-Fi network detected;
weather info has change;
I see something running in background and when one of the clauses hit, it will trigger and open the app.
How to get started?
How do I make sure my app won't be shut down?
As I read somewhere that Android OS will terminate apps if memory out occurs or consumes too much, and my app would consume a lot, making repeated measures/checks to see if situation changed.
Regards,
Pentium10
You need to use a Service for the part of your application that runs in the background.
You might find the Application Fundamentals document in the Android Developer Documentation helpful. It says this about Services:
A service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it.
In you case you might find the LocationManager Service helpful. It is a system Service which will you can use to notify your application based on GPS position.
However, I think you'll have to write your own Services to monitor Wi-fi, Bluetooth and weather.
You can use the AlarmManager Service to get your Service to perform particular tasks at certain intervals.
It depends on how & where you want to deploy your application. In my experience it boils down to
you create an application for a specific use case where battery drain matters less than accurate results (showcase situations, prototyping, ...)
you want to distribute the application to users.
In case 1) just create one service that aggressively polls the sensors / web services. Use the AlarmManager to send a REFRESH intent (AlarmService.setRepeating(...) ).
That REFRESH intent will restart the synchronization service everytime, even if it was killed by the system. onStart() will be called everytime the REFRESH intent is emitted. You can do heavyweight setup logic in onCreate() as this will be called everytime the service is created after it was destroyed. WARNING: This will possibly drain the battery very quickly.
In case 2) I would create several services and let the user configure different polling intervals for each service to limit battery drain. I can see for example that bluetooth should be polled more regulary than GPS as it is more likely that a bluetooth device suddenly appears than a user moving extremely fast.
Weather sounds extremely expensive (network lookup, possibly triggering a network connection!)
Please do not try to be too persistent with your app in case 2). It usually makes a lot of sense for a phone to kill memory / power draining services.

Categories

Resources