Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to always run a service in the background?

I am in the process of creating an app that is similar to the built-in SMS app.

What I need:

  • a service that is always running in the background
  • every 5 min. the service checks the current location of the device and calls a web service
  • if certain criteria are met, the service should generate a notification (just like the SMS app)
  • when the notification is clicked, the user is taken to the app (just like the SMS app)
  • when the app is installed the service should be started
  • when the device is rebooted, the service should be started

What I have tried:
- running a regular service which worked just fine until Android kills the service
- using the AlarmManager to make the 5 min. interval call to a service. But I was not able to make this work.

like image 578
Thomas H Avatar asked Apr 02 '10 11:04

Thomas H


People also ask

How do I run background services continuously?

This example demonstrates how do I run an android service always in background. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

Can a service run in background?

A service is simply a component that can run in the background, even when the user is not interacting with your application, so you should create a service only if that is what you need.


1 Answers

a service that is always running in the background

This is not possible in any real sense of the term, as you have discovered. It is also bad design.

every 5 min. the service checks the current location of the device and calls a web service

Use AlarmManager.

using the AlarmManager the make the 5 min. interval call to a service. But I was not able to make this work.

Here is a sample project showing how to use one, along with the use of WakefulIntentService so you stay awake while trying to do the whole Web service thing.

If you have continued problems with it, open up a new question about the specific things you are encountering with AlarmManager that are giving you grief.

like image 73
CommonsWare Avatar answered Sep 26 '22 06:09

CommonsWare