Search code examples
androidbackground-serviceandroid-intentservice

How to run an Android service in Background after it is swiped out by Recent activity?


I have a background service that should always run. It should wait for in-coming e-mails, when an e-mail arrives(to my old phone), it will trigger an action. (to send an sms to my new phone). Not a clever user-case but just learning android.

However, All the above works fine if I keep the app in 'Recent' apps. The moment I swipe it off, it doesn't work.

Any idea on how can I achieve this?

I have seen in some apps like Whatsapp, Facebook etc.. that even after we swipe off, there is a background service running to listen new notification etc. How do I achieve with my app??


Solution

  • For that you need to make service sticky return START_STICKY onStartCommand of the service. and in the doc its mentioed if the process is killed system will recreate again

    if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

    public class MyService extends Service {
    
        /*
         * (non-Javadoc)
         * 
         * @see android.app.Service#onBind(android.content.Intent)
         */
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            handler.postDelayed(run, 1000);
            return Service.START_STICKY;
        }
    
        private Runnable run = new Runnable() {
    
            @Override
            public void run() {
                handler.removeCallbacks(run);
                handler.sendEmptyMessage(0);
            }
        };
        private Handler handler = new Handler() {
    
            /*
             * (non-Javadoc)
             * 
             * @see android.os.Handler#handleMessage(android.os.Message)
             */
            @Override
            public void handleMessage(Message msg) {
                Log.e("handleMessage", "" + System.currentTimeMillis());
                handler.postAtTime(run, 1000);
            }
    
        };
    }