一分钟掌握Service生命周期

来源:互联网 发布:老凤祥网络旗舰店 编辑:程序博客网 时间:2024/05/16 08:44

Service有两种启动方式,1、通过startService启动。2、通过bindService()方式启动。下图说明了以两种方式启动时service的生命周期。

                                                                                 


写个例子说明

一、Service

package com.example.aidlexample;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.os.RemoteException;import com.example.aidlexample.Dog.Stub;public class DogDescribe extends Service {@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubSystem.out.println("通过startService方式调用" + "onStartCommand()执行 ");return super.onStartCommand(intent, flags, startId);}private DogBinder dogbinder;// 将IBinder对象返回给访问者@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubSystem.out.println("通过bindService调用" + "onBind()执行");return dogbinder;}@Overridepublic boolean onUnbind(Intent intent) {// TODO Auto-generated method stubSystem.out.println("onUnbind()");return super.onUnbind(intent);}@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();dogbinder = new DogBinder();}// 继承自动代码生成的类Stub(实现了IBinder接口)public class DogBinder extends Stub {@Overridepublic String getDogName() throws RemoteException {// TODO Auto-generated method stubreturn "xiaokeai";}@Overridepublic String getDogWeight() throws RemoteException {// TODO Auto-generated method stubreturn "30kg";}}}

二、startService()方式启动

该方式Service里的onStartCommand()方法执行

protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Intent it = new Intent();ComponentName comp = new ComponentName(MainActivity.this,DogDescribe.class);it.setComponent(comp);startService(it);}
执行结果:


三、bindService()方式启动

该方式Service里的onBind()方法执行,客户端调用unbindService()时,Service里的unBind()执行

protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Intent it = new Intent();ComponentName comp = new ComponentName(MainActivity.this,DogDescribe.class);it.setComponent(comp);bindService(it, conn, Service.BIND_AUTO_CREATE);}
执行结果:



不知道大家清楚了没有,关键是看清最上面一副图,哈哈...................

1 0