我正在尝试在我的应用程序开始时启动服务,我需要它重新启动服务,让用户决定强行关闭服务,即使应用程序正在运行(可以,他强行关闭应用程序,但是我需要在应用程序运行时阻止关闭服务)。
所以我开始扩展Application类,这就是我正在做的启动服务...
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);但是,这不会启动该服务。 虽然,使用startService似乎工作。 有任何想法吗?
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?
最满意答案
使用来自Application bindService()是没有意义的,因为您永远无法调用unbindService() 。
当然,最好的是,如果服务主动为用户提供价值,那么您的服务只会在内存中,而不仅仅是因为您的应用程序的某些其他组件正好被加载。 如果你按照你的Application中使用startService()计划,你就会走向泄漏这项服务的道路。 在Android中,“应用程序正在运行”作为生命周期构造没有真正的概念,因此您没有合理的时间来停止服务。
(顺便说一句,虽然Application有一个onTerminate()方法,但它永远不会被调用)
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)
更多推荐
发布评论