Janeshwar Yashpal
Janeshwar Yashpal

Reputation: 71

Application exit to keep it in background for some times

I am working on Android app where i using a service to fetch location on a time interval using timer. But if I keep my app in back ground for some time then application exit and its onCreate() method is re Called and my timer stops please tell me how I can keep running my application for long times.

timer  = new Timer();
timerTask = new TimerTask() {           
    @Override
    public void run() {                 
    }
};
timer.schedule(timerTask, 1000*60*4, 1000*60*4);

Upvotes: 0

Views: 347

Answers (2)

Piovezan
Piovezan

Reputation: 3223

A service that runs for a longer period of time is only worth its execution (and energy consumption) time if it delivers value to the user continually. It's not the case of a location poller, which only delivers value for short periods of time, depending on what you do with the polled location. In this case you should implement a service that will perform a short task (I mean task in the general sense, not a Task object) and then you must schedule your service to run from time to time. You can use Android's scheduling mechanism, called AlarmManager, to schedule your services.

There is a problem inerent to this approach, though: when the system is in battery-saving sleep state, your service has to acquire a wake lock in order to execute properly, then when finished release the wake lock for the system to go back to sleep state. Implementing this wake lock acquisition/release mechanism is not a trivial task.

I suggest you to use Commonsware's Location Poller implementation instead of implementing one yourself. It is well tested and solves the issue of acquiring/releasing a wake lock for your service to execute in the background.

If you insist in doing the polling yourself (e.g. to put already written code to use), I recommend using Commonsware's WakefulIntentService in order to avoid writing your own wake lock acquisition/release mechanism for your service. It's very easy to use.

Upvotes: 1

Matt Clark
Matt Clark

Reputation: 28589

Your solution for long running tasks is to use an Android Service.

A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. Each service class must have a corresponding declaration in its package's AndroidManifest.xml. Services can be started with Context.startService() and Context.bindService().

Upvotes: 0

Related Questions