Amit
Amit

Reputation: 3990

start a service in onCreate of Application

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?

Upvotes: 2

Views: 1678

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006574

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)

Upvotes: 5

Related Questions