start a service in onCreate of Application

有些话、适合烂在心里 提交于 2019-12-11 12:45:23

问题


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?


回答1:


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)



来源:https://stackoverflow.com/questions/8431631/start-a-service-in-oncreate-of-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!