0

I want to run my Android service(real-time notification service) after application installed and force it to work even application closed. This service responsible for listening my real-time notification server, when notification received I create Android notification and maybe run my app, if it is closed. I assume that my way is not correct for this case and there is another way working with real-time notification. I will be grateful if you give some link or a small explanation.

Anoop M Maddasseri
  • 10,213
  • 3
  • 52
  • 73
Thugmaster
  • 29
  • 6
  • If you want your service to run forever then create one service class in your project and override `onStartCommand()` method with `START_STICKY` return type, it will start your service again even if your app gets killed due to low memory issue or anything. If you want your service to be started without starting application when device reboots then add `RECEIVE_BOOT_COMPLETED` permission in your manifest. – Apurva Nov 30 '15 at 04:38

2 Answers2

2

the better approach to listening my real-time notification server, you've to use GCM. here you can start reading about GCM. and if you want to implement it yourself you have to write a service yourself. ex:

    public class ListenerService extends Service{
     @Override
     public void onStartCommand(Intent intent, int flags, int startId){


       return START_STICKY; //this will restart your service even though the system kills
      }

   // you can write other listener service method inside the service
    }

but still I recommend you to use GCM or other cloud messaging services instead of writing your own.

droidev
  • 7,352
  • 11
  • 62
  • 94
0

Extend the Android Service class in your class which you want to run in background always.Override the following method and return START_STICKY which makes your service to always run in background until you stop it.

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //your code here
        return START_STICKY;
    }

If you need to do any long running task than create a seperate thread for it and use it inside the service because service runs on main thread.

Harish Sharma
  • 360
  • 1
  • 2
  • 7