Hi Everyone I want to create location tracking application in android which runs in background even after user terminates application by left swipe from recent application. till now i have used intent service started from main activity but it gets killed when i terminate application.
Any other idea to implement this?
I have tried by registering location updates and doing work of service in onLocation changed event. but listener also gets unregister after application exists.
I don't need full code but i need approach to do this.
Have you tried to track in a Service? Without reference to the activity. You have the start the service from the activity for the first time.
Note: A service isn't killed by swiping from recent apps, rather it is killed by the OS when more ram is required. To restart it after its killed you have to return START_STICKY to onStartCommand i.e:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
Also, here you should register your LocationListener and perform whatever action you need.
And as always, remember to add permissions.
Related
I have a location service which I want to run at all times when the app is in the foreground, or in the background, but to stop when the app is closed (removed from the app tray)
My solution has been to start the service using START_NOT_STICKY and this seems to work, but I'm concerned by what the service documentation says about this command
START_NOT_STICKY says that, after returning from onStartCreated(), if the process is killed with no remaining start commands to deliver, then the service will be stopped instead of restarted. This makes a lot more sense for services that are intended to only run while executing commands sent to them. For example, a service may be started every 15 minutes from an alarm to poll some network state. If it gets killed while doing that work, it would be best to just let it be stopped and get started the next time the alarm fires.
So it seems that Android may kill off services when memory is low, and if using START_NOT_STICKY the service will not be restarted.
I tried using START_STICKY but this keeps the service running even after the app is closed.
What can I do to keep the service running at all times while the app is in the foreground or background, and stop after being closed, but without worrying about Android terminating it while the app is running?
Code here if it matters:
#Override
public int onStartCommand(Intent intent, int flags, int startId){
if (intent != null) {
extras = intent.getExtras();
// takes the messenger object and makes it local so when the messagereceiver sends an intent here, it won't overwrite the extras object
// and get rid of the messenger. Otherwise, getting an update from the notification controls would null out the messenger object
if (intent.hasExtra("MESSENGER")) {
Timber.e("MESSENGER ");
messenger = (Messenger) extras.get("MESSENGER");
}
}
return START_NOT_STICKY;
}
What can I do to keep the service running at all times while the app is in the foreground or background, and stop after being closed, but without worrying about Android terminating it while the app is running?
I'm not sure what "app tray" you're referring to or what exactly you mean by "closed" (Android apps are not things that are "closed", per se.
But, from your description, I'd think you want to do something like:
Start your Service when the user starts your app and bind to while the activity is in the foreground
If your activity is paused (or stopped), unbind from the service and start a foreground notification to keep the service alive and the user aware that it's still running
Instead of trying to detect when the app is "closed", which you can't really do, attach a "cancel" action to the foreground notification so the user can cancel it whenever they want
If that doesn't solve your issue, please elaborate on your use case and why you want to do this. I or others may be able to provide more / better / alternate suggestions with more specifics about what you're actually ultimately trying to achieve.
Hope that helps!
I have a function that reads the content of the Android clipboard every two seconds and communicates all changes with a remote server.
This works fine in the app is opened. But I need to be able to continue to log the clipboard changes after the app has been closed.
So I tried an IntentService but it doesn't appreciate long loops.
How can I run my infinite loop in the background?
I have a function that reads the content of the Android clipboard every two seconds and communicates all changes with a remote server.
Polling? You are doing it VERY wrong. You should use OnPrimaryClipChangedListener instead.
EDIT
communicates all changes with a remote server.
I just realised you are basically doing some bad things there and I am bit sceptical believing your users aware you literaly spying on them? Is your app in Google Play if so what's your app package id?
IntentService should be used to process single "request", from another application component, at time.
Use started service which should be more suitable for problem you describe. Started service runs until you manually stops it or until system gets out of resources and kill whole process.
Use START_STICKY as return from onStartCommand() method to automatically start it again when system kills it.
If you also start it in BroadcastReceiver with ACTION_BOOT_COMPLETED action service will be started after device boot.
Implement a Service and make it sticky by returning START_STICKY in onStartCommand (see Documentation):
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
when I open the activity of my project I call the startService(Intent intent) method to start a new Service.
When the activity is destroyed the service shouldn't be killed (because I didn't use the bindService() method), but the fact is that when I close my activity the service is killed and after a second the system creates a new Service (I verified that, the system calls again the onCreate() method of my service). What do I have to do to keep only one service ? Thank you
To have a service running independently of your application's main process and to be sure that Android does not kill it while it's doing something, there are two things you should do/try.
Run your service in a separate process. You can achieve this by adding the following attribute to your service declaration in the manifest:
android:process=":somenamehere"
When your service is running and you do not want it to be killed by the OS, you have to use the startForeground(int id, Notification notification) method. When the service finishes whatever is doing and can be killed by the OS, call stopForeground(boolean removeNotification). "startForeground" requires a notification as argument because every foreground service must display a notification so the user realizes about it
I hope this helps you.
I mean I hold the home button and then kill my activity from the list of app open
That does not "close" an activity. That terminates your process. The user is welcome to terminate your process whenever the user wants, whether via this means or through third-party task manager apps. There is nothing you can do about this -- you cannot stop the user from terminating your process. Since your process will stop for other reasons as well (e.g., sheer old age), you have plenty of reasons to handle this case.
Edit: Please refer to CommonsWare's answer
Old answer: You should override public int onStartCommand(Intent intent, int flags, int startId) method and return START_STICKY value as the mode of your service.
this will keeps your service working when the activity is destroyed or even when you exit your app unless you call stopService(Intent) explicitly
I would like to start my foreground service when my application is closed.
I tryed OnStop() but it's not a good idea for me because it can trigger multiple times and i which it to run only one instance.
I tryed OnDestroy() but it's simply doesn't trigger since i'm only using one activity in my whole app and most of time it is being kill with the SWIPE.
Is there a way i can detect when my application being kill or close ?
Thanks!
Only one instance of the service will run no matter how many times you start it. Each time a client starts the service the onStartCommand method fires. return Service.START_STICKY; to have your service stay running in the back ground after your app exits. But be warned if things get busy and the phone needs memory your service will be killed and you'll have to restart it like #Onur suggests with a conservative periodic AlarmManager intent.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// the service is started so after all clients are unbound it stays
// running
return Service.START_STICKY;
}
You can add your services description in manifest.xml stopWithTask="false" and in your sevice override the onTaskRemoved (Intent rootIntent) to know when activity that started the service is stopped for API level 14 and later.
Or you can set an alarm for some periods to check if your application is still running using AlarmManager. You should be careful with this tho, because it might consume battery based on the period you choose.
I build an application that collects data about the battery. In order to collect this data I need my application to run on the background in order to be able to collect this data.
How can I do it?
You need to change your activities into Service
if you're against using a service for whatever reason you can have it thread off, then get the data when the user calls the application to the front.
you can use the onStart, onPause, onResume functions as well as making the application single instance so when you run it again, it mearly pulls it up from memory (assuming Android doesn't kill it for some reason).
You can use ongoing notification to prevent it from being killed in the background and moveTaskToBack.
But as pentium10 says, the intended way to handle background processes is through a service which gathers the data you are looking for, then when the activity comes back to the front, it gets the data from the service and displays it.
- #Override public int onStartCommand(Intent intent, int flags, int
startId) {
handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY; }