1

I am trying to start a service when my app begins, and I need it the service to restart, incase a user decides to force close the service, even though the app is running(its ok, for him to force close the app, but i need to prevent closing of service while the app is running).

So i went about extending the Application class, and this is what I am doing to start the service...

ServiceConnection conn = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            Log.d("start","ok");
        }

        public void onServiceDisconnected(ComponentName className) {
        }
    };
    bindService(new Intent(this,DueService.class), conn, 0);

This, however, does not start the service. Though, using startService seems to work. Any ideas?

Amit
  • 3,952
  • 7
  • 46
  • 80

1 Answers1

4

Using bindService() from an Application is pointless, as you will never be able to call unbindService().

Best, of course, would be for your service to only be in memory if it is actively delivering value to the user, instead of just because some other component of your app happens to be loaded. As it stands, you are headed down a path towards leaking this service, if you go with your plan of using startService() from the Application. There is no real concept in Android of "the app is running" as a lifecycle construct, so you will not have a logical time to stop the service.

(BTW, while Application has an onTerminate() method, it will never be called)

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • so how would you suggest, that i can keep fetching live data from server, and if i cannot fetch the data, then the app cannot run properly. so i have 2 options now, either, to have the app crash, or to restart the service. – Amit Dec 08 '11 at 13:44
  • What is the issue if you use service without binding service that means as startService(intent); ? – Dharmendra Dec 08 '11 at 13:52
  • @Amit: call `bindService()` and `unbindService()` from each of your activities. Or, call `startService()` from your entry point activity (or, possibly, the `Application`) and keep track of when your activities come and go, so you can shut down that service with `stopService()` when it is no longer needed. – CommonsWare Dec 08 '11 at 20:01