基础篇(四) Service生命周期和进程内通信

来源:互联网 发布:都有什么数据库 编辑:程序博客网 时间:2024/06/05 03:50

Service默默无闻,做事情从不露面!

一. Service生命周期

启动Service的两种模式,分别是context.startService()和context.bindService()


(1) startService()启动模式下:

   依次调用其onCreate()-->onStartCommand(),进入运行状态。

   如果重复使用startService()启动Service,系统会找到刚才创建的Service实例,调用onStartCommand()

   如果我们想要停掉一个服务,可使用stopSelf()或stopService(),此时会调用onDestroy()。

(2) bindService()启动模式下:

   依次调用onCreate()-->onBind(),进入运行状态,调用者就可以和服务进行交互了。

   如果此调用者再次使用bindService()绑定Service,不做任何反应。

   如果我们需要解除与这个服务的绑定,可使用unbindService(),此时依次调用onUnbind()-->onDestroy()。

(3) 先startService()启动,再bindService()绑定:

   startService()启动,依次调用onCreate()-->onStartCommand()。

   bindService()绑定,调用onBind()。

   再unbindService()解绑,调用onUnbind()。

   最后使用stopSelf()或stopService()停止服务,才会调用onDestroy()。

(4) 先bindService()绑定,再startService()启动:
  先bindService()绑定,依次调用onCreate()-->onBind()。
  再startService()启动,调用onStartCommand()。
  再unbindService()解绑,调用onUnbind()。
  最后使用stopSelf()或stopService()停止服务,才会调用onDestroy()。
  启动关系和绑定关系。(弱关系和强关系)

startService()bindService()两种模式不同之处:

  startService()模式下,调用者与Service相互独立,即使调用者被销毁,只要没使用stopSelf()或stopService()停止这个Service

  Service仍会运行。

  bindService()模式下,调用者与Service生死与共的关系,一旦所有调用者被销毁,Service也立即被销毁

  当所有调用者与Service解绑,Service也随即调用onDestroy()销毁。

二. 进程内与Service通信

调用者与Service通信,需要bindService()模式下,借助Binder,ServiceConnection来实现。

public class MyService extends Service {private String name;@Overridepublic IBinder onBind(Intent intent) {return new MyBinder();}public class MyBinder extends Binder {public void set(String name) {this.name = name;}public String get() {return name;}}}


public class MainActivity extends Activity {private MyService.MyBinder myBinder;private ServiceConnection conn = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder binder) {myBinder = (MyService.MyBinder) binder;myBinder.set("myService");}@Overridepublic void onServiceDisconnected(ComponentName name) {}};@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);}public void bind(View view) {Intent intent = new Intent(this, MyService.class);bindService(intent, conn, Context.BIND_AUTO_CREATE);}public void unbind(View view) {unbindService(conn);}}



0 0
原创粉丝点击