Create a Long Running service - android

I need to create a service that runs alongside the android app,irrespective of which screen of the app the user is on.
The app is a chat application so when the device is offline the service should queue up all the messages that are being sent offline and when the device is connected it should sync all messages.
I have written code for the job scheduler to sync data automatically when the device is online but while the app is active i would like to handle this manually.

Creating a Long Running service.
Operating system still can terminate the service in low memory and possibly other situations. There are 2 ways to overcome this:
If you are implementing the service, override onStartCommand() and return START_STICKY as the result. It will tell the system that even if it will want to kill your service due to low memory, it should re-create it as soon as memory will be back to normal.
AlarmManager .A system service, which will execute actions periodically. That will ensure that if your service will be terminated, or even the whole process will die(for example with force close) - it will be 100% restarted by AlarmManager.
Thank you.

You can do this by simple following steps:
Create Simple Service and after first launch of app just start at splash screen.
In Service after getting one data you can call another request.
After that you can create one broadcast action globally which will always call every network changed.
At background you can sync again data and saved it to shared preferences or as per your your requirement.
For interval you can also using AlarManager.
A part from this you can simply create Service using JobSheduler in this you can assign job and time as well.
Refer link :
https://developer.android.com/reference/android/app/job/JobScheduler.html
Hopefully this logic will helps you.

You have to use a intent service with sticky instead of service for this which will be executed in a queue and do your work. And since it is a intent service it will be started automatically after sometime, when system kills the service process.

Related

How to have a continuous running background task on Android?

I'm fighting with the Android desire of killing everything which isn't active on the screen. My problem in few words:
I have a microcontroller which communicates with a processor on which Android runs;
the processor must keep active a watchdog on the microcontroller, resetting periodically (every one second) one of its registers; an application, say App B, accomplishes this duty;
on the processor I can be sure about the persistent existence of another application, say App A (or, however, if App A dies App B can die too because the system is compromised) which for now does nothing, in the future will accomplish other duties.
Which is the best way to implement App B?
I tried the following solution: App B contains a Bound Service, say Service A, to which App A can bind on; Service A starts a thread, say Thread A, which periodically resets the microcontroller watchdog. Thread A is launched when app A sends a command to Service A (e.g. START_WATCHDOG).
In my idea, Service A lives until App A lives (thanks to the binding), and so the process to which Service A belongs lives, and so also Thread A.
Unfortunately, from tests I see that sometimes (in a sporadic manner), after some time (sporadic time, too), with almost no work running on the system (except for App A, Service A and Thread A) the system kills Service A process, and so Thread A stops and the watchdog elapses.
When Service A dies, it is restarted (because it is a Bound Service and App A is still running) but, for now, I don't save the current state of Service (which simply consists on the START_WATCHDOG command arrival or not) and this is the reason for which the watchdog elapses.
So, I've got several questions about my solution:
is it ok and I simply need to save the current state of Service A in order to restore it when restarted?
should I discover better the reasons for which Service A, or better its process, is killed?
is there a better solution for my problem?
Thank you very much to everyone who will spend some time to help me.
Being not sure about periods in which your service runs you can try these:
Use foreground service. However, you might need to acquire a wakelock within your service start point if you need cpu in long time. Plus, a notification needs to be shown on phone status bar.
Use WorkManager-new api part of jetpack simplifying the use of alarm managers and jobschedulers- to schedule your tasks periodically. However if your frequency is higher than 1 per 5-10minute then you will need to take care of doze mode. If phone gets into doze, your tasks might be delayed till maintenance periods. A trick to apply here might be starting a foreground service when you catch activation of doze mode and return back to Workmanager logic in deactivation(if you don't want user to see the foreground service's notification). Do whatever you want in the foreground service like.
Use Firebase Cloud Messaging to push notification from your server to your users periodically for you to have a small amount of time to do work in background. When notification comes, OS grants you an interval to run a task.
Use Work manager it is easy to implement.

Android long time running service

I am working on an Android project and I need the app to work even when the device is locked.
The idea is to open the app that will start the (Intent)Service, the service processes the data all the time. The device can be locked/put away and after some time when the app is opened the service is manually stopped. The service should be running all the time in the background.
I have found information online, but I am not sure what to use and in which way..
I have found that the IntentService can be used. Also the service should run in a new thread. I need to process the data from gps all the time, should I use WakefulBroadcastReceiver?
Thank you.
IntentService is not necessarily what you want to use. It will automatically spawn a new thread just to handle an incoming Intent. Once all incoming Intents have been handled it will stop the Service. To have a long running Service, you would need to derive from Service and when it is started return START_STICKY from the onStartCommand() method, plus spawn your own thread to handle your background work.
If you need to monitor GPS, you'll have to manage that along with keeping the device awake using a WakeLock. Note that in Marshmallow, this gets more complicated because of the new Doze mode where even wakelocks are ignored.
Also, note that the way Android is architected there is still a chance that your application running the background Service may be killed. Android uses a unique process management technique based on memory pressure and user perceived priority to determine how long a process should stick around. I recommend reading up on the Service lifecycle in the documentation.
In android their is no fool proof way to ensure that your service runs forever because the LMK(low memory killer) when the system needs resources (based on a certain memory threshold) , kills the service then if it can restarts it. If you handle the restart properly the service will continue to run.
Services that are given foreground priority are significantly less likely to be killed off, so this might be your best bet. However their will be a notification of your service running the in the background on the menu bar up top. Foreground Service

Android service that doesn't close with application

I have been searching the net for hours. I am trying to make an application that has a UI interface and a service running in the background for SIP phone communication, kind of like Skype.
The UI starts and stops the service based on UI events, and the service stays logged in with a internet server in the background. I have found many articles talking about running the service on a separate thread(done), using startService as opposed to binding the service(done) but whenever I use the task manager to kill the application as a user might, I get an error popup saying my application has crashed and the service no longer runs.
How do programs like Skype, Facebook, or email clients do this?
Do I have to run these as separate applications using implicit intents?
Is there some settings I have to set in the manifest file other than declaring the service and it's name?
Better yet, is there a link to some page or source example using this kind of service?
EDIT: Sorry, I guess I wasn't clear. The service is stopping, and I don't want it to. I am trying to keep the service running in the background even after a user kills the application with the application manager.
One of the more confusing things with Service is that it is not run in a separate thread by default. Calling startService() as opposed to bindService() makes no difference in this regard. However, the binder mechanism will cause the Service exposed methods to be called in arbitrary thread context. In both cases, your Service is part of your application's process. If you kill it via the task manager or it crashes then the Service dies as well.
When you kill the app via the task manager and it pops up the message about the app dying, you have something misbehaving. Check logcat and it will point you at exactly where the crash happened.
If you need to have your Service running regardless of the UI, then don't stop the Service when your UI exits. You will still call startService() when your UI starts to re-connect (and possibly re-start it), but don't stop it unless you really want it stopped. Starts do not "stack". If something calls start 5x it doesn't take 5 stops to terminate the Service, only 1.

Android:nonstop Back ground service

I have started a service from my application and from that service a worker thread is started .I want my service to run even application goes background and until the user kills/exits the application.
But some cases my service got killed due to low memory ,then used sticky service or making the app to foreground to restart the service.
My issue is I dont want to lose the data between service ending and restarting time ,so is it possible to start another thread from service ondestroy method, but in this case how we can control that thread.
Please let me know is it the right approach ,and is this usecase achievable
I want my service to run even application goes background and until the user kills/exits the application.
This is not possible. The user can always get rid of your app, via Force Close in Settings, or via some device's version of the recent-tasks list.
But some cases my service got killed due to low memory
No, your process is terminated for low memory.
My issue is I dont want to lose the data between service ending and restarting time ,so is it possible to start another thread from service ondestroy method
No, because your process is being terminated.
Please let me know is it the right approach
Probably not. Very few apps need a service that runs constantly, which is why Android, and its users, go to great lengths to control such services. I would recommend that you try to find some solution to whatever your problem is that does not need a service running constantly.

How to make an application run continuously in android?

I am creating an application which sends the location information to the server. But when the back or home button is clicked the application is stopped. Is there a way to make the application run continuously in background and sends data to the server ?
Use a background Service. Services are application components which can run in the background without user interaction. A good tutorial on Service in android is from this.
You probably want to start the service on launch of your Activity, or you can register for system broadcasts like BOOT_COMPLETE to keep your service running from boot up.
However, keeping your service running throughout without user knowledge is a bad idea, and drains battery also. You probably want to wake up the service using AlarmManager, do processing, schedule next restart, and exit.
You need to run a Service class for your own application.
Refer docs for more information.

Categories

Resources