17

Can anyone tell me the way to keep a Service always running or restarting itself when the user close it? I've watched that facebook services restart when i clear memory. I don't want to make ForegroundServices.

weston
  • 54,145
  • 21
  • 145
  • 203
Marc Ortiz
  • 2,242
  • 5
  • 27
  • 46

2 Answers2

29

You should create a sticky service. Read more about it here.

You can do this by returning START_STICKY in onStartCommand.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("LocalService", "Received start id " + startId + ": " + intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}

Read also about application:persistent which is "Whether or not the application should remain running at all times". This is more troublesome - System will try not to kill your app which will effect others in the system, you should be careful using it.

auselen
  • 27,577
  • 7
  • 73
  • 114
  • I think it is not good practice to use `application:persistent`. I consider it can really increase battery consumption – busylee Jun 06 '14 at 09:13
  • 1
    @busylee you are right. it is bad for memory load, batter consumption. hopefully that's what last paragraph is about. However I prefer getting/giving straight answers rather than advice. – auselen Jun 06 '14 at 21:00
  • 1
    `application:persistent` looks great, but it has no effect for me on Android 4.3. [Apparently it only works for system apps](http://devescape.blogspot.com.au/2011/02/persistent-services-in-android.html). – Sam Feb 13 '15 at 12:23
  • Hi, I have set the flag as START_STICKY in onStartCommand but still the process closes after sometime. How can i solve this ? – prakashpun Sep 09 '15 at 11:42
  • 2
    This method should call super.onStartCommand(intent, flags, startId) – Rafouille May 26 '16 at 14:25
8

I copied this from a service I used in an app I did before.

ITS IMPORTANT TO NOT UPDATE ANY UI. because you have no user interface in services. this applies to Toasts as well.

good luck

public class nasserservice extends Service {
    private static long UPDATE_INTERVAL = 1*5*1000;  //default

    private static Timer timer = new Timer(); 
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate(){
        super.onCreate();
        _startService();

    }   

    private void _startService()
    {      
        timer.scheduleAtFixedRate(    

                new TimerTask() {

                    public void run() {

                        doServiceWork();

                    }
                }, 1000,UPDATE_INTERVAL);
        Log.i(getClass().getSimpleName(), "FileScannerService Timer started....");
    }

    private void doServiceWork()
    { 
        //do something wotever you want 
        //like reading file or getting data from network 
        try {
        }
        catch (Exception e) {
        }

    }

    private void _shutdownService()
    {
        if (timer != null) timer.cancel();
        Log.i(getClass().getSimpleName(), "Timer stopped...");
    }

    @Override 
    public void onDestroy() 
    {
        super.onDestroy();

        _shutdownService();

        // if (MAIN_ACTIVITY != null)  Log.d(getClass().getSimpleName(), "FileScannerService stopped");
    }

}
Sam
  • 40,644
  • 36
  • 176
  • 219
Hossam Alaa
  • 663
  • 5
  • 9
  • sorry for the late comment. the answer is Yes. – Hossam Alaa Jun 05 '14 at 13:18
  • This doesn't seem to make any difference for me; it didn't stop the service from being killed, and it didn't cause the service to be restarted after it was killed. – Sam Feb 13 '15 at 12:30
  • I think the timer will not garbage collected, since it's different thread and the thread is keep running, holding reference to the service itself. I wonder why this solution isn't work for you @Sam? – HendraWD Mar 02 '16 at 08:20
  • @HendraWijayaDjiono, it's been too long for me to remember how I tested it, so I'm not sure! :) – Sam Mar 04 '16 at 07:52