Jude Fernandes
Jude Fernandes

Reputation: 7517

Create a Long Running service

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.

Upvotes: 4

Views: 4494

Answers (3)

Akash
Akash

Reputation: 711

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.

Upvotes: 1

Manoj Srivastava
Manoj Srivastava

Reputation: 670

You can do this by simple following steps:

  1. Create Simple Service and after first launch of app just start at splash screen.
  2. In Service after getting one data you can call another request.
  3. After that you can create one broadcast action globally which will always call every network changed.
  4. At background you can sync again data and saved it to shared preferences or as per your your requirement.
  5. 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.

Upvotes: 1

Rameshbabu
Rameshbabu

Reputation: 611

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:

  1. 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.

  2. 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.

Upvotes: 2

Related Questions