服务:如果使用bindService启动,则不会调用onTaskRemoved

时间:2014-06-09 19:53:46

标签: android android-service android-service-binding

我有一个已实施onTaskRemoved()方法的服务 当使用startService()启动服务时,通过滑动将应用从recent-apps-list中删除时,将调用函数onTaskRemoved()

但如果服务是以bindService()启动的,则onTaskRemoved()从未调用过。

在使用onTaskRemoved()启动应用后,如何通过轻扫将应用从recent-apps-list中删除,如何进行服务调用bindService()

如果以:

开头,Android会调用以下生命周期方法
1. bindService():
Activity﹕ onCreate()
CustomService﹕ onCreate()
CustomService﹕ onStart()
CustomService﹕ onStartCommand()
CustomService﹕ onBind()
// Here we swipe to remove app from recent-apps-list
CustomService﹕ onTrimMemory()

2. startService():
ActivityA﹕ onCreate()
CustomService﹕ onCreate()
CustomService﹕ onStart()
CustomService﹕ onStartCommand()
CustomService﹕ onBind()
// Swipe to remove app from recent-apps-list
CustomService﹕ onTrimMemory()
CustomService﹕ onTaskRemoved() // <===== 
CustomService﹕ onUnbind()

1 个答案:

答案 0 :(得分:14)

可以绑定或启动服务,也可以两者兼而有之。这取决于您如何实施onStartCommandonBind说文档。

http://developer.android.com/guide/components/services.html

但是,如果您希望您的服务同时保持并通过IBinder与客户交谈,那么只需启动该服务然后绑定到它。

startService(new Intent(context, CustomerService.class));
// Bind to the service
bindService(new Intent(context, CustomerService.class),
                        mConnection, Context.BIND_AUTO_CREATE);